你可以使用FormControl的valueChanges属性来监听表单控件的值变化,并在addControl时触发。
下面是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements OnInit {
  form: FormGroup;
  ngOnInit() {
    this.form = new FormGroup({
      control1: new FormControl(''),
      control2: new FormControl('')
    });
    this.form.get('control1').valueChanges.subscribe((value) => {
      if (value) {
        this.addControl('control2');
      } else {
        this.removeControl('control2');
      }
    });
  }
  addControl(controlName: string) {
    if (!this.form.contains(controlName)) {
      const control = new FormControl('');
      this.form.addControl(controlName, control);
    }
  }
  removeControl(controlName: string) {
    if (this.form.contains(controlName)) {
      this.form.removeControl(controlName);
    }
  }
}
在上面的代码中,我们创建了一个表单组件,其中有两个控件control1和control2。我们在control1的valueChanges订阅中监听值的变化。如果值存在(非空),则调用addControl方法添加control2控件,否则调用removeControl方法移除control2控件。
希望对你有帮助!