如何通过选择角度选项显示输入字段?

时间:2018-11-05 05:00:52

标签: angular angular-material

这里我有一个material native select,并且在此选择下拉列表中,当%option那段时间我想按%输入字段显示折扣时,以及当我选择number option那段时间我想显示的时候,这两个选项(%和数字)按数字折扣输入字段,如何通过选择选项显示输入字段?

<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>

1 个答案:

答案 0 :(得分:1)

您可以只使用*ngIf,但是首先需要在ngModel上定义select以获得two-way binding,然后在*ngIf中使用它的变量< / p>

<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>

此外,您还应该在discountType文件中定义component.ts,以避免在aot编译期间出错。详细了解*ngIf指令here