在我的形式:
<form>
   <label class="form-check-label">
     <input [(ngModel)]="options.o1" name="o1"
            type="checkbox" class="form-check-input" >
     Option 1
   </label>
   <label class="form-check-label">
     <input [(ngModel)]="options.o2" name="o2"
            type="checkbox" class="form-check-input" >
     Option 2
   </label>
</form>
我想在两个复选框中的一个被更改时被通知,而不是通过向每个复选框添加事件处理程序,而是通过向表单添加事件处理程序,实际上表单中还有更多字段.
yur*_*zui 31
您可以获得如下NgForm指令:
HTML
<form #form="ngForm">
   ...
</form>
TS
@ViewChild('form') ngForm: NgForm;
然后再听valueChanges上NgForm.form
TS
ngOnInit() {
  this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
    console.log(x);
  })
}
ngOnDestroy() {
  this.formChangesSubscription.unsubscribe();
}
我使用了公认的答案,并在此基础上创建了一个值得关注的演示版本。
TS文件
export class AppComponent {
  
  options: any;
  formChangesSubscription: any;
  @ViewChild('form') ngForm: NgForm;
  updated: any;
  constructor() {
    this.options = { o1: true, o2: false }
  }
  ngOnInit() {
    this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(form => {
      console.log(form);
      this.updated = form;
    })
  }
  ngOnDestroy() {
    this.formChangesSubscription.unsubscribe();
  }
}
HTML文件
<form #form="ngForm">
  <label class="form-label">
     <input [(ngModel)]="options.name" name="name"
            type="text" class="form-input" >
     
   </label>
   <label class="form-check-label">
     <input [(ngModel)]="options.o1" name="o1"
            type="checkbox" class="form-check-input" >
     Option 1
   </label>
   <label class="form-check-label">
     <input [(ngModel)]="options.o2" name="o2"
            type="checkbox" class="form-check-input" >
     Option 2
   </label>
</form>
<label>{{updated?.o1}}</label>
<label>{{updated?.o2}}</label>
<label>{{updated?.name}}</label>
https://stackblitz.com/edit/angular-change-template-form?file=src/app/app.component.ts
| 归档时间: | 
 | 
| 查看次数: | 8704 次 | 
| 最近记录: |