-
Notifications
You must be signed in to change notification settings - Fork 1
/
base-dynamic-field.component.ts
79 lines (64 loc) · 2.18 KB
/
base-dynamic-field.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Input, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DynamicField } from '../fields';
import { Subscription } from 'rxjs';
/**
* Base class for Dynamic Fields
*/
export class BaseDynamicFieldComponent<T extends DynamicField> implements OnInit, OnDestroy {
@Input() field: T;
@Input() form: FormGroup;
@Input() editing = true;
@Input() isHorizontal: boolean;
@Input() labelWidth: number;
control: FormControl;
visible = true;
public hideLabelOnEdit = false;
/** If true, the read-only state will show the value obtained from the formattedValue method;
* otherwise, will keep the component to manage this behavior.
*/
public useFormattedValueOnReadonly = true;
private valueChangeSubscription: Subscription;
ngOnInit() {
this.control = this.form.controls[this.elementId] as FormControl;
if (this.field.visibilityFn) {
const formRoot = this.form.root; // Make sure to get the root form, even for nested FromGroups
this.valueChangeSubscription = formRoot.valueChanges.subscribe(val => {
this.visible = this.field.visibilityFn(val);
if (!this.visible && !this.field.keepValueWhenHiding) {
this.control.setValue(null, { emitEvent: false });
}
});
this.visible = this.field.visibilityFn(formRoot.value);
}
}
ngOnDestroy() {
if (this.valueChangeSubscription) {
this.valueChangeSubscription.unsubscribe();
}
}
/**
* Property to be used as the Form Element ID
*/
get elementId(): string {
return String(this.field.key);
}
get instance(): BaseDynamicFieldComponent<T> {
return this;
}
get isOptional(): boolean {
return !this.field.validators || !this.field.validators.find(el => el === Validators.required);
}
get isEditing(): boolean {
return this.editing && !this.field.readOnly;
}
get formattedValue(): string {
return this.form.controls[this.elementId].value || '-';
}
displayFieldCss(): { [k: string]: boolean } {
return {
'has-error': this.control.touched && this.control.invalid,
'has-feedback': this.control.touched && this.control.invalid
};
}
}