I need some advices to realise a form in my angular2 application.
I have a situation object who contains three importants things : id, name, type In a form, I create a dropdown list with the situations name (I use a service to get the list and use a ngFor directive to display) According to the type of the selected situation, I build a formGroup with those own formControls (I use an onChange function on the dropdown list) I use the type to display the new inputs in the template (many situations can have the same type). I have a problem in my template with this code, the selected value doesn't appear anymore when I select a value ...
Below, a snippet of my code to understant what I'm talking about :
Template:
<form [formGroup]="myForm" (ngSubmit)="saveForm()" novalidate>
<select class="form-control" [(ngModel)]="selectedSituation" (change)="onChangeSituation()" formControlName="name">
<option [ngValue]="situation" *ngFor="let situation of situationsArray">{{situation.name}}</option>
</select>
<div *ngIf="selectedSituation?.type == 1">
<!-- some fields -->
</div>
<div *ngIf="selectedSituation?.type == 2">
<!-- other fields -->
</div>
</form>
Component:
situationsArray: string[];
selectedSituation: any;
type: any;
constructor(
private _fb: FormBuilder
) { }
createDefaultForm(){
this.myForm = this._fb.group({
name: ['', Validators.required]
// inputs not concerning by dropdown list
});
}
createType1Form(){
this.myForm = this._fb.group({
name: ['', Validators.required]
// inputs for type = 1
});
}
createType2Form(){
this.myForm = this._fb.group({
name: ['', Validators.required]
// inputs for type = 2
});
}
ngOnInit(){
this.createDefaultForm(); // a formGroup for the inputs who aren't concerned by the dropdwon list
this.getListSituations(); // a service to get the situations list
}
onChangeSituation(): void{
console.log(this.selectedSituation);
if(this.selectedSituation.type == 1) {
this.createJobForm();
} else
if(this.selectedSituation.type == 2) {
this.createPeForm();
} else
if(this.selectedSituation.type == 3) {
this.createPeaForm();
} else
this.createDefaultForm();
}
Do you have any idea concerning the display problem ? Maybe I use a wrong practice ...
I'm stuck for a while now, all your advices will be welcome, Thx.