简体   繁体   中英

How to detect in Angular 8 whether a value in angular is changed by user or a method call has changed it

I have a select element in which value is getting assigned by ngOnit call.

HTML:

<select name="duration" [(ngModel)]="exercisePlan.duration" (ngModelChange)="onChange($event)"> 
    <option *ngFor="let duration of durations" [value]="duration.value">{{duration.title}}</option> 
</select> 

TS:

durations =  [{ title: "15 seconds", value: 15 }, 
              { title: "30 seconds", value: 30 }, ...]

ngOnit() {
    this.exercisePlan.duration = durations[0];
}

onChange(event) {
    console.log("How to show that change is done by user but not by some method call");
}

So the value is not assigned by user and is made available by some method (ngOnInit, in this case).

Whereas when I select a value from dropdown then how to know whether user has made the selection from select options?

Similar to that suppose if I add a Reset button in my HTML and on click of Reset I change value of my Select element, so how to distinguish in onChange() method whether the change is done by user or any other method call has made the changes to that element model?

Hi i would recommend to use FormControl. I would paste the correct code and then i would explain.

ngOnit() {
      this.control.setValue(
        // value to set
        durations[0], 
        // this prevent the control from notify the change (optional)
        { emitEvent: false }
      );
    }

<select name="duration" [formControl]="control">
  <option value="">Select a value</option>
  <option *ngFor="let duration of durations" [ngValue]="duration.value">{{duration.title}}</option>
</select> 

on the component:

valueDetection() {
this.formControl.valueChanges
      .subscribe(value => {
        // value is the value selected or assigned
        // here you can do logic
      });
}

In this example the FormControl change either when the user select a option or on code by a method. The FormControl is a observable so it will be activate every time the value change and you can control logic associated with that change inside the subscribe. Now i would make 2 assumption here.

First one is that you want to make code change without triggering the change. That is archived by the values in the setValue method.

Second you want to deal with logic depending if it is from code or not the change. This one is tricky. In order to know if the change is from code you must check the dirty and and touched values of the FormControl. The second choice is to make an object like this: { value: 'the value', fromCode: true} and deal with the second value on the subscribe

More info about FormControl

More info about Selects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM