Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate input field type with angular 2 and set the type of the field

Tags:

html

angular

I am new to angular 2 and trying to dynamically generate a bunch of input fields based on models using angular 2. Some fields are password fields. I want to make the input fields type to password if so. I have written something like this :

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

now problem is I want to make the field password if the field.name is password I am thinking adding something like this to the input

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

now if I do this, All my other fields which are not password simply does not get rendered. Only password field gets rendered. What am I doing wrong.(i am very new to angular2)

like image 819
nanobots Avatar asked Jan 31 '26 10:01

nanobots


1 Answers

This might work but as far as I remember, setting type dynamically is not supported (but might be worth a try):

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

This is the safe option:

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

If field.name is 'Password', the first is added, otherwise the 2nd input is added to the DOM.

like image 122
Günter Zöchbauer Avatar answered Feb 03 '26 06:02

Günter Zöchbauer