首页 > 解决方案 > 如何通过选择角度选项来显示输入字段?

问题描述

在这里我有一个material native select,在这个选择下拉列表中有两个选项(% 和数字),当 % 选项那个时候我想按 % 输入字段显示折扣时,当我选择数字选项那个时候我想按数字输入字段显示折扣它是怎样的可以通过选择选项来显示输入字段吗?

<div>
  <mat-form-field>
    <input matInput placeholder="Enter Price" type="number" [(ngModel)]="newObj.newPrice" name="newPrice">
  </mat-form-field>

  <mat-form-field>
    <select matNativeControl>
      <option value="percentagewise">%</option>
      <option value="numberwise">Number</option>
    </select>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter Discount By %" [(ngModel)]="newObj.newDiscountByPercentage" name="newDiscountByPercentage">
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter Discount By Number" type="number" [(ngModel)]="newObj.newDiscountByNumber" name="newDiscountByNumber">
  </mat-form-field>  
</div>

标签: angularangular-material

解决方案


您可以使用*ngIf,但首先您需要定义ngModelonselect以获取two-way binding,然后使用它的变量 in*ngIf

<mat-form-field>
    <select matNativeControl [(ngModel)]="discountType">
      <option value="percentagewise">%</option>
      <option value="numberwise">Number</option>
    </select>
  </mat-form-field>

  <mat-form-field *ngIf="discountType == 'percentagewise'" >
    <inputmatInput placeholder="Enter Discount By %" [(ngModel)]="newObj.newDiscountByPercentage" name="newDiscountByPercentage">
  </mat-form-field>

  <mat-form-field *ngIf="discountType == 'numberwise'" >
    <input matInput placeholder="Enter Discount By Number" type="number" [(ngModel)]="newObj.newDiscountByNumber" name="newDiscountByNumber">
  </mat-form-field>

此外,您应该在文件中定义discountTypecomponent.ts避免aot编译期间的错误。在此处阅读有关*ngIf指令的更多信息


推荐阅读