Angular 4 个选择在 *ngFor 选项中不起作用

Angular 4 selected not working in option with *ngFor

<option [selected]="true"> 在 Angular 4 中不起作用,如果它也存在 ngFor。

模板:

<form [formGroup]='myForm'>

  <div class="col-sm-9 col-md-4">
    Not working selected, with ngFor
    <select formControlName="nationality" class="form-control">
      <option *ngFor="let elem of nationalityList" [ngValue]="elem.code" [selected]="elem.code=='ITA'">{{ elem.description}}</option>
    </select>
  </div>

  <div class="col-sm-9 col-md-4">
    Working selected, without ngFor
    <select formControlName="nationality" class="form-control">
      <option [ngValue]="nationalityList[0].code" [selected]="nationalityList[0].code=='ITA'">{{ nationalityList[0].description}}</option>
      <option [ngValue]="nationalityList[1].code" [selected]="nationalityList[1].code=='ITA'">{{ nationalityList[1].description}}</option>
    </select>
  </div>

</form>

分量:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: 'app-prova',
  templateUrl: './prova.component.html',
  styleUrls: ['./prova.component.css']
})
export class ProvaComponent implements OnInit {

  myForm:FormGroup = new FormGroup({
    nationality: new FormControl('')
  });

  nationalityList = [
    { description: 'NATIONALITY_ITALIAN', code: 'ITA' },
    { description: 'NATIONALITY_FOREIGN', code: 'EST' }
  ];

  constructor() { }

  ngOnInit() {
  }

}

输出:

所以问题是:为什么 selected 不能与 ngFor 一起使用?是错误还是我遗漏了什么?如何让它工作?谢谢。

如果这有帮助,我曾经为此声明一个 NGmodel 并根据我的需要在我的 ts 文件中初始设置它的值,就像这样:

   <select [(ngModel)]="myval" formControlName="nationality" class="form-control"> 
    <option *ngFor="let elem of nationalityList" [ngValue]="elem.code" [selected]="elem.code=='ITA'">{{ elem.description}}</option> 
    </select>

在我使用的 ts 文件中:

export class ProvaComponent implements OnInit {
  myval:any; // or your type
  myForm:FormGroup = new FormGroup({
    nationality: new FormControl('')
  });

  nationalityList = [
    { description: 'NATIONALITY_ITALIAN', code: 'ITA' },
    { description: 'NATIONALITY_FOREIGN', code: 'EST' }
  ];

  constructor() { }

  ngOnInit() {
   this.myval = this.nationlaityList[0]; // for example
  }

}

可能并不总是有效,但在某些情况下确实有效

你不应该使用 selected,试试这个:

<form [formGroup]="myForm">
  <select formControlName="nationality" class="form-control">
    <option *ngFor="let elem of nationalityList" [ngValue]="elem.code">
      {{ elem.description}}
    </option>
  </select>
</form>

并将您的 myForm 定义更改为:

myForm:FormGroup = new FormGroup({
  nationality: new FormControl('ITA')
});