Angular 2 selecting option from select list based on passed in parameter

梦想与她 提交于 2019-12-10 12:13:39

问题


Hi hope someone can advise what I am missing.

In my plunker demo I have an edit button that on clicking gives a static id of 2 right now. (this simulates an id parameter coming into this component in my real project)

What I am trying to do is take the passed in id and find the user and select them in the dropdownlist so it then populates my other fields, like it currently does if you just select a user from the select list.

In my code I can see I have the id and can find the full name that matches.I can also populate the id field, but not set the select list selected value to the full name any assistance appreciated.

Html currently showing dropdownlist and id field with two way databinding

  <select [(ngModel)]="tradesman">
<option>Select</option>
<option [ngValue]="v" *ngFor='let v of _tradesmen'>{{ v.fullname}}</option>

Plunker demo showing where I am up to

Thanks Andy


回答1:


From the question what i understood is, you have an id, and you have to choose the value in the select box with respect to this id. I hope it is on page load, thats why i am using ngOnInit().

ngOnInit() {  
    this.myId =2;    /* ur id */

    let index = this._tradesmen.findIndex(x => x.id == this.myId);

    if(index>=0){    /* if there is value in the array that matches the id value*/
      this.tradesman = this._tradesmen[index];
    } 
  }

You don't have to change anything in your html file.

  <select [(ngModel)]="tradesman">
    <option>Select</option>
    <option [ngValue]="v" *ngFor='let v of _tradesmen'>{{ v.firstname }} {{ v.lastname }}</option>
  </select>



回答2:


It should be [value]="v" not [ngValue]="v". And from your plunker code, your class doesn't implement OnInit



来源:https://stackoverflow.com/questions/46909238/angular-2-selecting-option-from-select-list-based-on-passed-in-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!