如何检测Angular 2反应/动态形式的一个元素发生的变化? [英] 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# .我的表单当前包含输入类型text
和file
.我使用change事件捕获文件上传任务,因此我需要检测file
输入元素中的更改,而不是text
输入元素中的更改.这是我遇到问题的地方.使用*ngSwitch
或*ngIf
构建的表单似乎不会触发change
事件.我创建了一个 plunker ,可用于重现我面临的问题./p>
如果我在每个表单元素中检测到更改,则该表单可以正常工作. (在插件示例中为form2)
请重读以下链接中的"punker",以复习我所面临的问题. 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)
时无法触发事件的原因.因为您的开关盒基于控件类型,并且所有表单元素的控件类型均为textbox
.将file
类型的输入的控制类型从textbox
更改为file
.
I am trying to detect the change in one specific form element that was built using reactive forms.
I used *ngFor
and *ngSwitch
directives to build a reactive form as demonstrated in 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 that can be used to recreate the issue I am facing.
The form works fine if I detect changes in each form element. (form2 in the plunker example)
Please see plunker in the link below for a recreation of the issue I am facing. https://plnkr.co/edit/1dMfn7gmR3rHq6xcgr2a?p=preview
Does anyone know how to resolve this issue?
This should work, if you use rxjs;
this.form1.controls['image1'].valueChanges.subscribe((data) => {
console.log(data);
});
Put this code in ngOnInit
method after you create form1
form group. Whenever value of image1
changes, subscriber log the data
.
Edit
Since the value of input which type is file
never changed, you can not watch the changes as I said, sorry for that.
In plunker, all of your control type of form elements are textbox
. This is the reason why you can not fire the event when you write (change)
in only one element. Because your switch case is based on control type and all of form element's control type is textbox
. Change the control type of inputs which types are file
from textbox
to file
.
这篇关于如何检测Angular 2反应/动态形式的一个元素发生的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!