问题描述
我使用的是 Angula 9,并且在 ReactiveForm 中有一个 mat-select 输入。我想在我的表单之外,在同一个 html 模板内显示选定的选项 - 而不是输入值。
我正在这样做:
<div class="basic-container">
<mat-form-field>
<mat-label>Category*</mat-label>
<mat-select type="text" aria-label="Number" formControlName="category">
<mat-option *ngFor="let option of categories" [value]="option.id">
<p>{{option.name}}</p>
</mat-option>
</mat-select>
</mat-form-field>
</div>
<p>{{myForm.value.category}}</p>
知道如何到达显示的选项而不是输入值吗?
解决方法
那不可能使用显示的文本。但是,您可以更改您的值以包含选项 [value]="option"
。您需要在解析表单时获取 id
:
<mat-form-field>
<mat-select type="text" aria-label="Number" formControlName="category">
<mat-option *ngFor="let option of categories" [value]="option">
<p>{{option.name}}</p>
</mat-option>
</mat-select>
</mat-form-field>
<p>{{myForm.value.category.name}}</p>
或者如果你不想这样做,你可以使用一个函数来获取正确的类别:
<mat-form-field>
<mat-select type="text" aria-label="Number" formControlName="category">
<mat-option *ngFor="let option of categories" [value]="option.id">
<p>{{option.name}}</p>
</mat-option>
</mat-select>
</mat-form-field>
<p>{{getCategoryById(myForm.value.category)}}</p>
getCategoryById(categoryId: number): Category {
return this.categories.find(({ id }) => id === categoryId);
}