如何检测 Angular 2 reactive/dynamic 表单的一个元素发生的更改?

How do I detect changes that occur to one element of an Angular 2 reactive/dynamic form?

我正在尝试检测使用反应式表单构建的一个特定表单元素的变化。

我使用 *ngFor*ngSwitch 指令构建了一个响应式表单,如 https://angular.io/docs/ts/latest/cookbook/dynamic-form.html#. My form currently contains input type text and file. I use the change event to capture the file upload task so I need to detect changes in the file input element but not the text input element. This is where I run into the problem. The form built using *ngSwitch or *ngIf doesn't seem to trigger the change event. I have created a plunker 中所示,可用于重现我面临的问题。

如果我检测到每个表单元素的变化,表单工作正常。 (plunker 示例中的 form2)

请参阅下面 link 中的 plunker,以重现我面临的问题。 https://plnkr.co/edit/1dMfn7gmR3rHq6xcgr2a?p=preview

有谁知道如何解决这个问题?

如果你使用 rxjs,这应该可以工作;

this.form1.controls['image1'].valueChanges.subscribe((data) => {
     console.log(data);
});

创建 form1 表单组后,将此代码放入 ngOnInit 方法中。每当 image1 的值发生变化时,订阅者都会记录 data.

编辑

由于输入file类型的值从未改变,你不能像我说的那样看到变化,很抱歉。

在plunker中,你所有的表单元素控件类型都是textbox。这就是为什么只在一个元素中写入 (change) 时无法触发事件的原因。因为您的 switch case 是基于控件类型的,而所有表单元素的控件类型都是 textbox。将类型为file的输入控制类型由textbox更改为file.