html - Angular 4 - creating input type dynamically with ngFor -
since got form lot of different input fields, avoid having gigantic html template want put fields data inside objects , create template dynamically using ngfor
.
code until now.
stub.ts - store data
export const my_data = [ { placeholder: 'first name', name: 'name', model: 'model.name'}, { placeholder: 'last name', name: 'lastname', model: 'model.lastname'}, { placeholder: 'age', name: 'age', model: 'model.age'} ];
component.ts
import { component, oninit } '@angular/core'; import {my_data} './stub'; @component({ selector: 'app-valutazione-insert', templateurl: './valutazione-insert.component.html', styleurls: ['./valutazione-insert.component.css'] }) export class valutazioneinsertcomponent implements oninit { model: = {}; data = my_data; constructor() { } ngoninit() {} submit() { console.log('data submitted: ', this.model); } }
template.html
<div id="datirichiesta" [hidden]="datirichiestaclicked" > <div class="form-group" *ngfor="let d of data"> <input type="text" class="form-control" placeholder="{{d.placeholder}}" [(ngmodel)]=d.model name="{{d.name}}" onfocus="this.placeholder = ''" (blur)="this.placeholder = d.placeholder"/> </div> </div>
now, got things don't work:
- even if on rendered html attributes correctly set, placeholder value takes model value
- the behaviour of placeholder
onfocus
,onblur
not working - most important, if try submit values these not passed controller
now every problem disappear if use input type properties set statically. there way achieve want?
thanks!
stubs.ts
it better renamed model
modelpropname
make more clear.
this means first name
set in name
property of model: = {}
object, , on.
export const my_data = [ { placeholder: 'first name', name: 'name', modelpropname: 'name'}, { placeholder: 'last name', name: 'lastname', modelpropname: 'lastname'}, { placeholder: 'age', name: 'age', modelpropname: 'age'} ];
template.html
<form id="datirichiesta" [hidden]="datirichiestaclicked" (submit)="submit()"> <div class="form-group" *ngfor="let d of data"> <input type="text" class="form-control" placeholder="{{d.placeholder}}" [(ngmodel)]="model[d.modelpropname]" name="{{d.name}}" (focus)="$event.target.placeholder = ''" (blur)="$event.target.placeholder = d.placeholder"/> </div> <button>submit</button> </form>
when submit form should in console:
data submitted: object {name: "...", lastname: "...", age: "..."}
Comments
Post a Comment