Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 553
Unknown developer Avatar asked Nov 09 '17 10:11

Unknown developer


People also ask

What is the difference between form control and form group?

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.

What is the difference between formControlName and FormControl?

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

Can you use form control without form group?

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.


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

like image 181
Unknown developer Avatar answered Nov 03 '22 11:11

Unknown developer


 const year =  <FormControl>(this.formApply.get('currentUKAddress.years'));
year.valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })
like image 26
Milad Avatar answered Nov 03 '22 09:11

Milad