Angular 2 selecting option from select list based

2019-06-09 03:36发布

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

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-09 03:42

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

查看更多
叼着烟拽天下
3楼-- · 2019-06-09 03:45

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>
查看更多
登录 后发表回答