export class ApplyComponent implements OnInit {
formApply: FormGroup;
postCodeInput: boolean = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.formApply = this.fb.group({
firstName: ["", Validators.required],
currentUKAddress: this.fb.group({
flat: ["", Validators.required],
years: ["", Validators.required]
})
});
this.onChanges();
}
onChanges(): void {
...
}
I want to listen for changes in years. No matter what I tried inside onChanges()
I cannot find why nothing works...
I tried:
- this.formApply.get('currentUKAddress.years').valueChanges.subscribe(data => {
console.log('Form changes', data);
})
- this.formApply.controls.currentUKAddress.get('years').valueChanges.subscribe(data => {
console.log('Form changes', data);
})
- this.formApply.controls.currentUKAddress.controls['years'].valueChanges.subscribe(data => {
console.log('Form changes', data);
})
and other stuff as well. In all cases I am getting Typescript compiler error either: property does not exist on type AbstractControl or Object is possibly null.
Just as a form control instance gives you control over a single input field, a form group instance tracks the form state of a group of form control instances (for example, a form). Each control in a form group instance is tracked by name when creating the form group.
[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name.
Sometimes, we don't need a FormGroup, as our form might only consist of a single form control. Think of a search field that let's you search for products in an e-commerce application. Technically, we don't even need a <form> element for that.
For some reason type checker is unable to make a right decision. So Non-null assertion operator (!) came to my rescue:
this.formApply.get('currentUKAddress.years')!.valueChanges.subscribe(data => {
console.log('Form changes', data);
})
works like a charm...
const year = <FormControl>(this.formApply.get('currentUKAddress.years'));
year.valueChanges.subscribe(data => {
console.log('Form changes', data);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With