如何检测 Angular 2 反应式/动态形式的一个元素发生的变化? [英] How do I detect changes that occur to one element of an Angular 2 reactive/dynamic form?

查看:20
本文介绍了如何检测 Angular 2 反应式/动态形式的一个元素发生的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测使用反应式表单构建的一个特定表单元素的变化.

I am trying to detect the change in one specific form element that was built using reactive forms.

我使用 *ngFor*ngSwitch 指令来构建响应式表单,如 https://angular.io/docs/ts/latest/cookbook/dynamic-form.html#.我的表单当前包含输入类型 textfile.我使用更改事件来捕获文件上传任务,因此我需要检测 file 输入元素中的更改,而不是 text 输入元素.这就是我遇到问题的地方.使用 *ngSwitch*ngIf 构建的表单似乎不会触发 change 事件.我创建了一个 plunker 可用于重现我面临的问题.

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.

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

The form works fine if I detect changes in each form element. (form2 in the plunker example)

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

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?

推荐答案

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

This should work, if you use rxjs;

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

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

Put this code in ngOnInit method after you create form1 form group. Whenever value of image1 changes, subscriber log the data.

编辑

由于 file 类型的 input 的值从未改变,所以你不能像我说的那样看到变化,抱歉.

Since the value of input which type is file never changed, you can not watch the changes as I said, sorry for that.

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

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

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