有条件地设置输入类型

时间:2019-03-09 01:14:08

标签: angular

在下面的代码中,有一种方法可以根据组件属性有条件地设置输入的类型,例如:

<input type="typeof(model[key])">[ng-type]="typeof(model[key])"<input type="typeof(model.key)">或其他类似的东西?

<form #myForm="ngForm" (ngSubmit)="sendQuery()">
  <div *ngFor="let key of modelKeys">
      {{key}} 
      <input  #myInput [ng-type]="typeof(model[key])" name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" required *ngIf="key==='q'" appNoSpecialChars/>
      <input  #myInput [ng-type]="typeof(model[key])" name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" minlength = '2' maxlength='4' *ngIf="key==='stars'" appNoSpecialChars />      
      <input  #myInput [ng-type]="typeof(model[key])" name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" *ngIf="key!=='q' && key!=='stars'" appNoSpecialChars/> 
      <p *ngIf="!myForm.form.get(key)?.valid" >Not valid</p> 
  </div>
  <button type="submit" [disabled]="!myForm.valid">Submit</button> 
</form>

1 个答案:

答案 0 :(得分:0)

请尝试使用诸如*ngIf[ngSwitch]之类的结构指令来显示正确的输入,而不是绑定到type属性。像这样:

<form>
    <div *ngFor="let key of modelKeys">
    {{key}}
    <ng-container [ngSwitch]="model[key]">
        <input #myInput *ngSwitchCase="'text'" type="text" name="{{key}}" placeholder="Enter {{key}} Here" />
        <input #myInput *ngSwitchCase="'email'" type="email" name="{{key}}" placeholder="Enter {{key}} Here" />
        <input #myInput *ngSwitchCase="'password'" type="password" name="{{key}}" placeholder="Enter {{key}} Here" />
    </ng-container>
</div>
<button type="submit">Submit</button>