监听嵌套表单组的表单控件内的变化

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 {
        ...
    }

我想听 的变化。无论我在 onChanges() 中尝试了什么,我都找不到为什么什么都不起作用... 我试过了:

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

以及其他内容。在所有情况下,我都会收到 Typescript 编译器错误: 属性 在类型 AbstractControl 上不存在 或者 对象可能为空

ngOnChanges 仅对 input/output 变量有用。

如果您想收听文本 (?) 输入的变化,您必须

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

在你的 TS

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

为另一个做这个,你就可以开始了!如果它不是文本输入,请告诉我,在这种情况下 (input) 会发生变化(例如,对于 select 是 (change)

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

由于某种原因,类型检查器无法做出正确的决定。所以 Non-null assertion operator (!) 来救我了:

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

很有魅力...

你可以这样做..

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

我有相同的表单结构,我做了类似下面的事情:

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

    }
 )

None 以上解决方案对我有用。所以我直接听currentUKAddress而不是years。

希望这个想法对某人有所帮助。

Angular版本:7