微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

访问选择输入显示的文本 - Angular

如何解决访问选择输入显示的文本 - Angular

我使用的是 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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。