我有一个选择,其选择为options
挂钩中的HTTP请求返回的数据生成了ngOninit
。
看起来像这样:
ngOnInit() {
this.documentosService.buscaParametros(this.request).subscribe(res => {
this.tipoDocumento = res["general"];
}
这是HTML代码:
<select class="form-control pv-0" formControlName="tipoFactura" name="tipoFactura">
<option *ngFor="let documento of tipoDocumento">
{{documento.par_deslargo01}}</option>
</select>
如果不是动态生成的,则可以将selected
指令写入第一个option
元素,但是在这种情况下,我不知道如何实现。我需要在组件首次加载时选择第一个选项。
如何实现?谢谢。
非常简单。你可以做这样的事情。
<select class="form-control pv-0" formControlName="tipoFactura" name="tipoFactura">
<option *ngFor="let documento of tipoDocumento; let i = index" [selected]="i === 0">
{{documento.par_deslargo01}}</option>
</select>
更新-使用反应形式
当您使用Angular Reactive Forms时,您可以使用反应式表格的功能来做您想做的事情。您可以按照以下方式将选择的option
设置为select
。
HTML
<form [formGroup]="myForm">
<select formControlName="mySelect">
<option *ngFor="let coutry of countries" [value]="coutry">{{coutry}}</option>
</select>
</form>
TS
countries: any = ['Sri Lanka', 'USA', 'UK', 'Australia'];
selectedCoutry = 'Australia';
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
mySelect: new FormControl('')
});
}
ngOnInit() {
this.myForm.get('mySelect').setValue(this.selectedCoutry);
}
为了回答提出的问题,ngFor公开了许多有用的模板变量,其中有“ first”,如果您在第一项上,则为true,否则为false:
<option *ngFor="let documento of tipoDocumento; let first" [selected]="first">
{{documento.par_deslargo01}}</option>
还提供索引,偶数和奇数。
但是,由于您使用的是反应形式,因此建议的方法是跳过所有内容并设置形式控制值:
ngOnInit() {
this.documentosService.buscaParametros(this.request).subscribe(res => {
this.tipoDocumento = res["general"];
this.form.get('tipoFactura').setValue(this.tipoDocumento[0].par_deslargo01)
// not sure what your form variable really is
}
}
这将自动在选项列表中选择该值