Angular2 *ngFor in select list, set active based on string from object

前端 未结 2 1844
不知归路
不知归路 2021-02-01 02:09

I\'m trying using the ngFor on my select DropDownList. Have loaded in the options which should be in the dropdown.

The code you see here:

&         


        
相关标签:
2条回答
  • 2021-02-01 02:34

    This should work

    <option *ngFor="let title of titleArray" 
        [value]="title.Value" 
        [attr.selected]="passenger.Title==title.Text ? true : null">
      {{title.Text}}
    </option>
    

    I'm not sure the attr. part is necessary.

    0 讨论(0)
  • 2021-02-01 02:43

    Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

    Setting the passenger.Title with a value that equals to a title.Value should work.

    View:

    <select [(ngModel)]="passenger.Title">
        <option *ngFor="let title of titleArray" [value]="title.Value">
          {{title.Text}}
        </option>
    </select>
    

    TypeScript used:

    class Passenger {
      constructor(public Title: string) { };
    }
    class ValueAndText {
      constructor(public Value: string, public Text: string) { }
    }
    
    ...
    export class AppComponent {
        passenger: Passenger = new Passenger("Lord");
    
        titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                      new ValueAndText("Lord", "Lord-Text")];
    
    }
    
    0 讨论(0)
提交回复
热议问题