Binding select element to object in Angular

后端 未结 14 1510
走了就别回头了
走了就别回头了 2020-11-22 02:41

I\'d like to bind a select element to a list of objects -- which is easy enough:

@Component({
   selector: \'myApp\',
   template: `

My Application&

14条回答
  •  礼貌的吻别
    2020-11-22 03:21

    It worked for me:

    Template HTML:

    I added (ngModelChange)="selectChange($event)" to my select.

    On component.ts:

      listOptions = [
        { id: 0, name: "Perfect" },
        { id: 1, name: "Low" },
        { id: 2, name: "Minor" },
        { id: 3, name: "High" },
      ];
    

    An you need add to component.ts this function:

      selectChange( $event) {
        //In my case $event come with a id value
        this.model.myListOptions = this.listOptions[$event];
      }
    

    Note: I try with [select]="oneOption.id==model.myListOptions.id" and not work.

    ============= Another ways can be: =========

    Template HTML:

    I added [compareWith]="compareByOptionId to my select.

    On component.ts:

      listOptions = [
        { id: 0, name: "Perfect" },
        { id: 1, name: "Low" },
        { id: 2, name: "Minor" },
        { id: 3, name: "High" },
      ];
    

    An you need add to component.ts this function:

     /* Return true or false if it is the selected */
     compareByOptionId(idFist, idSecond) {
        return idFist && idSecond && idFist.id == idSecond.id;
     }
    

提交回复
热议问题