简体   繁体   中英

How do I ensure a select change event fires AFTER ngmodel is set in Angular2?

I have a select element that has a basic (change) handler attached to it along with an ngmodel. When an <option> with a ng value is set, the change handler fires. The problem is that the [(ngModel] does not have the new values yet.

<div>
        <button style="margin: 8px 0;" (click)="getNextLink()" class="btn btn-primary btn-sm pull-right">Next Label ></button>
        <div class="form-group">
            <label for="filter-word">Select Word To Filter:</label>
            <select [(ngModel)]="selectedLabels[selectedLabels.length]"
                    (change)="onChange($event)"
                    class="form-control"
                    id="filter-word"
                    name="filter-word">
                <option *ngFor="let label of (primaryTopic.topics) | stringFilter: selectedLabels" [ngValue]="label">
                    {{label}}
                </option>
            </select>
        </div>
    </div>

Here is the component code:

  public onChange(event: any): void {
    console.log('event', event);
    console.log('this.selectedLabels', this.selectedLabels); // undefined
    debugger; 
  }

How do I respond ONLY when the ngModel has been updated?

Use ngModelChange instead:

(ngModelChange)="onChange($event)"

There is no way to specify in what order event handlers should be executed. Because ngModelChange is itself emitted by NgModel after the bound property is updated, this should fit your needs.

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