Binding select element to object in Angular

后端 未结 14 1509
走了就别回头了
走了就别回头了 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:44

    Just in case someone is looking to do the same using Reactive Forms:

    <form [formGroup]="form">
      <select formControlName="country">
        <option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
      </select>
      <p>Selected Country: {{country?.name}}</p>
    </form>
    

    Check the working example here

    0 讨论(0)
  • 2020-11-22 03:47

    You can do this too without the need to use [(ngModel)] in your <select> tag

    Declare a variable in your ts file

    toStr = JSON.stringify;

    and in you template do this

     <option *ngFor="let v of values;" [value]="toStr(v)">
          {{v}}
     </option>
    

    and then use

    let value=JSON.parse(event.target.value)
    

    to parse the string back into a valid JavaScript object

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