Angular: selected on option of select doesn't work as excepted while using along with ngModel

前端 未结 2 1416
你的背包
你的背包 2020-12-01 20:09

I have an array of objects(named users) which will be shown as options of dropdownlist. and I have another objects list(named selectedU

相关标签:
2条回答
  • 2020-12-01 20:57

    selected is not supported with [(ngModel)]="selectedUser3".

    To make an item selected, the value (for string only) or ngValue property value needs to match the value in selectedUser3.

    this.selectedUser3 = this.users[2];
    

    By default only object identity is checked, therefore another object instance with the same properties and values doesn't match. You can customize comparison using compareWith

    https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html

    <select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
        <option *ngFor="let country of countries" [ngValue]="country">
            {{country.name}}
        </option>
    </select>
    compareFn(c1: Country, c2: Country): boolean {
        return c1 && c2 ? c1.id === c2.id : c1 === c2;
    }
    
    0 讨论(0)
  • 2020-12-01 21:00

    Answer to conflicts between [(ngModel)] and [selected]

    after some research and debug, I find that while using ngModel on select, angular will run it's own SelectMultipleControlValueAccessor for select and own directive for option of select which lead selected to be ignored.

    In the third example(example plunker), after ngModel is used, although function bind to [selected] will be called, but it's result is simply ignored.


    Comments

    • comment1:
      The problem can be solved by binding [(ngModel)] and [ngValue] with same instance of objects.
    • comment2:
      The problem can also be solved by using compareWith directive, see Gunter' s anwser
    • comment3:
      This will happen also for single select, see SelectControlValueAccessor and directive for option.

    New Info:

    See also this issue for more information.

    0 讨论(0)
提交回复
热议问题