如何听角度模板驱动的形式变化 [英] how to listen of angular template driven form changes

查看:69
本文介绍了如何听角度模板驱动的形式变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以我的形式:

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

每当两个复选框之一发生更改时,我都希望得到通知,而不是通过向每个复选框添加事件处理程序,而是通过向表单添加事件处理程序,实际上在表单中会有更多字段./p>

I want to be informed whenever one of the two checkboxes is changed, not by adding an event handler to each of the checkboxes but by adding an event handler to the form, in reality there are much more fields in the form.

推荐答案

您可以持有NgForm指令,例如:

You can get hold of NgForm directive like:

html

<form #form="ngForm">
   ...
</form>

ts

@ViewChild('form') ngForm: NgForm;

,然后在NgForm.form

ts

ngOnInit() {
  this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
    console.log(x);
  })
}

ngOnDestroy() {
  this.formChangesSubscription.unsubscribe();
}

ng-run演示

ng-run demo

这篇关于如何听角度模板驱动的形式变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆