Search code examples
formsangulartypescriptangular-forms

Listen for changes inside form control of a nested form group


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.


Solution

  • 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...