【问题标题】:Dynamically generate input field type with angular 2 and set the type of the field使用angular 2动态生成输入字段类型并设置字段的类型
【发布时间】:2021-05-06 00:48:32
【问题描述】:

我是 Angular 2 的新手,并试图根据使用 Angular 2 的模型动态生成一堆输入字段。有些字段是密码字段。如果是这样,我想让输入字段类型为密码。我写了这样的东西:

<div *ngFor="let field of connector.type.configFields">
    <label>{{field.name}}</label>
    <input [(ngModel)]="field.value" />
</div>

现在的问题是如果 field.name 是密码,我想设置字段密码 我正在考虑在输入中添加这样的内容

<div *ngFor="let field of connector.type.configFields">
    <label>{{field.name}}</label>
    <input [(ngModel)]="field.value" *ngIf="field.name =='Password'" type="password"  />
</div>

现在,如果我这样做,我所有其他不是密码的字段都不会被渲染。只有密码字段被呈现。我做错了什么。(我对angular2很陌生)

【问题讨论】:

    标签: html angular


    【解决方案1】:

    这可能有效,但据我记得,不支持动态设置type(但可能值得一试):

    <input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"/>
    

    这是安全的选择:

    <input [(ngModel)]="field.value" *ngIf="field.name === 'Password'" type="password"  />
    <input [(ngModel)]="field.value" *ngIf="field.name !== 'Password'" type="text"  />
    

    如果field.name 是'Password',则添加第一个输入,否则将第二个输入添加到 DOM。

    【讨论】:

    • 哇,第一个答案奏效了。非常感谢我不知道你可以这样做。所以在 Angular 2 中,我们必须设置 else?。是不是像其他语言一样,我们可以只做 if 而不会打扰 else?如果我没有指定其他结果,那么结果将不仅仅是默认值?
    • *ngIf 是关于整个元素的。如果条件为真/假,则将其添加到 DOM 中/从 DOM 中删除。 [type]="..." 仅与属性有关。我不知道允许检查一个条件并返回一个值并且在条件不匹配时什么都不做的有效表达式。 [type]="field.name === 'Password' ? 'password' : null" 也可能有效。
    【解决方案2】:
     Other way around you can interpolate the type attribute of input.
     Demo :https://plnkr.co/edit/zfXqCEmaNkulRcWSs1ah?p=preview
    
     connector: Array<any>;
     constructor() {
     this.name = 'Angular2';
     this.connector = [
      { type: 'text', value: 'firstName' },
      { type: 'text', value: 'lastName' },
      { type: 'numeric', value: 'age' },
      { type: 'password', value: 'password' },
      { type: 'text', value: 'city' }];
     }
     inputType(type) {
     console.log(type);
     let inputType;
     switch (type) {
      case 'text':
        inputType = 'text';
        break;
      case 'numeric':
        inputType = 'number';
        break;
      case 'datetime':
        inputType = 'date';
        break;
      case 'password':
        inputType = 'password';
        break;
      default:
      }
      return inputType;
       }
    
    
    <div *ngFor="let field of connector">
    <label>{{field.value}}</label>
    <input [(ngModel)]="field.value"  type={{inputType(field.type)}}  />
    </div>
    

    【讨论】:

      【解决方案3】:

      可以这样直接添加 <div *ngFor="let form of contactForm.controls"> <input name={{form.label}} type={{form.controlType}}>
      </div>

      【讨论】:

      • 根据类型,我将其作为模型中的字符串,将分配给类型,它的工作方式就像您在输入中分配字符串类型一样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多