0

I have a huge model-driven form which it's fields may affect each other's behavior, For example:

If value of field A changes, Value of field B should be obtained from server,Or if value of field C changes, Field D should be disabled & etc.

In order to detect the changes I use valueChanges:

this.form.controls['a'].valueChanges.subscribe(data=>{
    //do some staff
});
this.form.controls['b'].valueChanges.subscribe(data=>{
    //do some staff
});
.
.
.

(Note that I can't say this.form.valueChanges because my form has about 50 fields). Everything looks fine but this approach makes my ngOnInit() a little messy. My question is:

Is there any better/more efficent solution for situations like this?Subscribing too many observables in ngOnInit doesn't make any problems?How can I improve my code?

soroush gholamzadeh
  • 2,616
  • 1
  • 22
  • 30

1 Answers1

1

It will be cleaner to use angular event binding on the template. Combine that with ngModel for bidirectional data-binding, and it can make your component code much cleaner.

For example:

<input type="text" formControlName="a" [(ngModel)]="inputValue" (change)="doSomething($event)">

You can do event binding in Angular2 for DOM events like change, click, keyup, blur etc.

Edit:

  • change gets fired only on clicking outside the input textbox.
  • keyup is a better option compared to change.

See this Plunk to compare the difference.

Santanu Biswas
  • 4,699
  • 2
  • 22
  • 21
  • using (change) will be delayed,look at here: http://stackoverflow.com/a/34616143/4221872 – soroush gholamzadeh Jan 24 '17 at 10:47
  • 1
    Actually `change` event is fired only on `blur`. If you want the event to be fired as you type then you can use `keyup`, the delay between `keyup` and `valueChanges.subscribe` is negligible. I have put together a [Plunk](http://plnkr.co/edit/1glzZEvFmO08IUwTIbAQ?p=preview) for you to verify this. [http://plnkr.co/edit/1glzZEvFmO08IUwTIbAQ?p=preview](http://plnkr.co/edit/1glzZEvFmO08IUwTIbAQ?p=preview) – Santanu Biswas Jan 24 '17 at 11:37
  • The main problem of change is working with select tags,If I `console.log()` the value of a ` – soroush gholamzadeh Jan 24 '17 at 12:12
  • Well.. I am not sure how you are testing. Please see the [Plunk](http://plnkr.co/edit/1glzZEvFmO08IUwTIbAQ?p=preview). I have added a select element to it now, and you can see that `(change)` gives back the new value!! – Santanu Biswas Jan 24 '17 at 12:36
  • Thanks! I got it ;-) – soroush gholamzadeh Jan 24 '17 at 12:41