curl -v --http1.1 https://stream.wikimedia.org/v2/stream/recentchange
在Angular 4中不起作用,如果它也出现在ngFor。
模板:
<option [selected]="true">
组件:
<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>
输出:
所以问题是:为什么没有选择使用ngFor?这是一个错误还是我错过了什么?如何使它工作?谢谢。
答案 0 :(得分:1)
如果这有用,我曾经根据我的需要声明一个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
}
}
可能并不总是有效,但在某些情况下可以完成工作
答案 1 :(得分:1)
你不应该使用选择,试试这个:
<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')
});