Listen for changes inside form control of a nested form group

Viewed 9384
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.

5 Answers

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);
        })

ngOnChanges is only useful for input/output variables.

If you want to listen to changes in your text (?) inputs, you must do

<input type="text" formControlName="flat" (input)="flatChangeListener($event)">

In your TS

flatChangeListener(event) {
  // event should contain the input value.
}

Do this for the other one and you're good to go ! And if it's not a text input, please tell me so, the (input) would change in this case (for instance, it's (change) for a select)

you can do it like this ..

this.formApply.get('currentUKAddress').get('years').valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })

I had the same form structure and I did something like below:

this.formApply.controls.currentUKAddress.valueChanges.subscribe(
 currentUKAddress =>
    {
      console.log("years", currentUKAddress.years) // Here you can check whatever 
                                                   //  value is coming in years.

    }
 )

None of the above solutions worked for me. So I listened to currentUKAddress instead of years directly.

Hope this Idea helps someone.

Angular version: 7

Related