How do I detect changes that occur to one element

2019-04-16 04:38发布

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?

1条回答
ら.Afraid
2楼-- · 2019-04-16 05:08

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.

查看更多
登录 后发表回答