将默认值设置为下拉列表角度



我希望在下拉列表角度材质中选择第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>

有人能告诉我们在加载页面时需要做什么来设置默认值吗?

.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);
}
}

这里有一个例子: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';

最新更新