我希望在下拉列表角度材料中将第0个索引选择为默认值。
<mat-form-field>
<mat-select
name="dashboard"
(selectionChange)="showDashboard(dashboard)"
[(ngModel)]="dashboard"
[(value)]="selected"
>
<mat-option *ngFor="let status of CLIENT_STATUS" [value]="status.id">
{{ status.name }}
</mat-option>
</mat-select>
</mat-form-field>
任何人都可以告诉在加载页面时必须执行哪些操作来设置默认值吗?
答案 0 :(得分:2)
.html文件
<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
<mat-select placeholder="Category" formControlName="patientCategory">
<mat-option>--</mat-option>
<mat-option *ngFor="let category of patientCategories" [value]="category">
{{category.name}} - {{category.description}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
.ts文件
export class TableBasicExample {
patientCategory: FormGroup;
patientCategories=[{
id:1,
name:'name 1',
description:'description 1'
},{
id:2,
name:'name 2',
description:'description 2'
},{
id:3,
name:'name 3',
description:'description 3'
}]
constructor(private fb: FormBuilder){}
ngOnInit() {
this.patientCategory = this.fb.group({
patientCategory: [null, Validators.required]
});
const toSelect = this.patientCategories.find(c => c.id == 3);
this.patientCategory.get('patientCategory').setValue(toSelect);
}
}
答案 1 :(得分:0)
这里是一个例子: HTML文件:
<mat-form-field>
<mat-label>Test</mat-label>
<mat-select [(value)]="selected">
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
</mat-select>
</mat-form-field>
,然后在您的TS文件中设置默认值:
selected = 'option1';