【发布时间】:2018-07-04 13:56:55
【问题描述】:
我需要一些建议来在我的 angular2 应用程序中实现表单。
我有一个情境对象,它包含三个重要的东西:id、name、type 在一个表单中,我创建了一个带有情况名称的下拉列表(我使用服务来获取列表并使用 ngFor 指令来显示) 根据所选情况的类型,我用那些自己的formControls构建了一个formGroup(我在下拉列表中使用了onChange函数) 我使用类型来显示模板中的新输入(许多情况可以具有相同的类型)。 我的模板中有此代码的问题,当我选择一个值时,所选值不再出现...
下面是我的代码的 sn-p,以了解我在说什么:
模板:
<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>
组件:
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();
}
您对显示问题有任何想法吗? 也许我使用了错误的做法......
我现在被困了一段时间,欢迎您的所有建议,谢谢。
【问题讨论】:
标签: angular