简体   繁体   中英

Angular2 trigger ngModelChange automatically

So I have the following code:

<div class="form-group">
<label for="backings_select">Backing Single</label>
<select class="form-control"
        required
        [(ngModel)]="selectedBacking" 
        name="backings_select"
        (ngModelChange)="storeValueRedux($event, count)">
  <option *ngFor="let backing of backings" [ngValue]="backing.id" [selected]="backings.length === 1">{{backing.name}}</option>
</select>

It populates a select box with results from a service call, if the array length is 1, it auto selects the only option available, this works fine.

However, by default the select box uses a value from the component as its default value.

So when the service call is made, if the array only has a length of one, the value of the model is changing, but because its being auto selected (not by user input) the storeValueRedux event is not firing.

However, if the array has more than one entry, and then is selected by a user, the function is called and works as required. Is there anyway to trigger ngModelChange in the instance that backings.length = 1?

You can't use a condition inside your method calls in HTML but you can use change and handle the condition inside your method as below

 <select class="form-control"
    required
    [(ngModel)]="selectedBacking" 
    name="backings_select"
    (change)="storeValueRedux($event, count)">
        <option *ngFor="let backing of backings" [ngValue]="backing.id"
            [selected]="backings.length === 1">{{backing.name}}</option>

 selectedBacking:any{};
  backings:any[]=[
    {id:1, name:'a'},
    {id:2, name:'a'}
    ]

  storeValueRedux(a,b){
     if(this.backings.length!=1){
    console.log(this.selectedBacking);
    console.log(a,b);
  }
 }

LIVEDEMO

The service that returned my backings was an observable, so I modified the subscribe from:

.subscribe(
        results => {this.backings = results},
        error => console.log(error),        
);  

to:

.subscribe(
        results => {this.backings = results, this.testBackingLength()},
        error => console.log(error),        
);  

And then added:

testBackingLength(){
    /* If the length of the arrau is only one, the template auto selects it
    and does not trigger ngOnChange, so we need to manually trigger it here,
    this function is called from the subscribe a few lines up */
    if (this.backings.length === 1) {
    this.storeValueRedux(this.backings[0]['id'], this.count)}
}

So each time my service is called, it tests the length of the array. If the length of the array is 1, it will auto call my function.

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