// limitations under the License.
// ========================LICENSE_END===================================
// /
-//
-import { Component, Input, OnInit } from '@angular/core';
+import { Component, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, ControlContainer, FormBuilder, FormControl, FormGroup, FormGroupDirective, ValidatorFn, Validators } from '@angular/forms';
+import { EventEmitter } from '@angular/core';
@Component({
selector: 'nrcp-no-type-policy-editor',
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class NoTypePolicyEditorComponent implements OnInit {
+ @Input() policyJson: string = null;
+ @Output() validJson: EventEmitter<string> = new EventEmitter<string>();
- @Input() instanceForm: FormGroup;
- @Input() policyJson: string;
+ instanceForm: FormGroup = new FormGroup({});
constructor(
private formBuilder: FormBuilder) { }
- ngOnInit(): void {
- this.instanceForm.addControl(
- 'policyJsonTextArea', new FormControl(this.policyJson, [
- Validators.required,
- jsonValidator()
- ])
- )
- }
+ ngOnInit(): void {
+ this.instanceForm.addControl(
+ 'policyJsonTextArea', new FormControl(this.policyJson, [
+ Validators.required,
+ this.jsonValidator()
+ ])
+ )
+ }
- get policyJsonTextArea(): AbstractControl {
+ get policyJsonTextArea(): AbstractControl {
return this.instanceForm ? this.instanceForm.get('policyJsonTextArea') : null;
}
formatJsonInput(): void {
this.policyJson = formatJsonString(JSON.parse(this.policyJsonTextArea.value));
}
-}
-export function formatJsonString(jsonToFormat: any): string {
- return JSON.stringify(jsonToFormat, null, 2);
-}
+ jsonValidator(): ValidatorFn {
+ return (control: AbstractControl): { [key: string]: any } | null => {
+ const notValid = !this.isJsonValid(control.value);
+ this.handleJsonChangeEvent(notValid, control.value);
+ return notValid ? { 'invalidJson': { value: control.value } } : null;
+ };
+ }
-export function jsonValidator(): ValidatorFn {
- return (control: AbstractControl): { [key: string]: any } | null => {
- const notValid = !isJsonValid(control.value);
- return notValid ? { 'invalidJson': { value: control.value } } : null;
- };
-}
+ handleJsonChangeEvent(notValid: boolean, newValue: string): void {
+ let json = newValue;
+ if (notValid) {
+ json = null;
+ }
+ this.validJson.emit(json);
+ }
-export function isJsonValid(json: string): boolean {
- try {
- if (json != null) {
- JSON.parse(json);
- return true;
- } else {
+ isJsonValid(json: string): boolean {
+ try {
+ if (json != null) {
+ JSON.parse(json);
+ return true;
+ } else {
+ return false;
+ }
+ } catch (jsonError) {
return false;
}
- } catch (jsonError) {
- return false;
}
}
+
+export function formatJsonString(jsonToFormat: any): string {
+ return JSON.stringify(jsonToFormat, null, 2);
+}