Dynamically Generate Input Field Type With Angular 2 And Set The Type Of The Field
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 t
Solution 1:
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.
Solution 2:
Other way around you can interpolate the type attribute of input.
Demo :https://plnkr.co/edit/zfXqCEmaNkulRcWSs1ah?p=previewconnector: 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>
Solution 3:
You can add directly like this
<div *ngFor="let form of contactForm.controls">
<input name={{form.label}} type={{form.controlType}}>
</div>
Post a Comment for "Dynamically Generate Input Field Type With Angular 2 And Set The Type Of The Field"