我试图使用angular动态绑定控件,但是由于某些原因它没有正确绑定。我在这里想念的。
<ng-container *ngFor='let ui of uiData'>
<ng-container *ngIf="ui.position === 'left'">
<div class="p-grid">
<div>
<label>{{ ui.label }}</label>
</div>
<div>
<input id="input" type="text" [(ngModel)]= "ui[model]">
</div>
</div>
</ng-container>
</ng-container>
<div>
<button pButton type="button" (click)="SubmitData();" label="Save"></button>
</div>
我想做的就是让用户单击按钮时在字段上输入数据。
export class DynamicLoadComponent implements OnInit {
uiData:any;
userData:UserDataModel = null;
constructor() {
this.uiData = [
{ label:"test1",position: "left", control: "textbox",model: "userData.child1.docNumber" },
{ label:"test1",position: "left", control: "textbox", model: "userData.child1.ws"},
{ label:"test1",position: "right", control: "textbox", model: "userData.child1.ns" },
{ label:"test1",position: "left", control: "textbox", model: "userData.child1.dueDate" },
{ label:"test1",position: "left", control: "textbox",model: "userData.child1.initDate" },
]
}
SubmitData(){
console.log(this.userData);
}
}
模型类如下
export class UserDataModel {
child1: {
docNumber: string;
ws: number;
ns: number;
dueDate: string;
initDate: string;
}
}
答案 0 :(得分:1)
您的变量uiDate
是一个对象数组,因此,我的猜测是您应将项目命名为[(ngModel)] = "ui.model"
而不是[(ngModel)] = "ui[model]"
编辑
尝试一下:
x.component.html:
<ng-container *ngFor='let ui of uiData'>
<ng-container *ngIf="ui.position === 'left'">
<div class="p-grid">
<div>
<label>{{ ui.label }}</label>
</div>
<div>
<input id="input" type="text" [(ngModel)]= "ui.model">
</div>
</div>
</ng-container>
</ng-container>
<div>
<button pButton type="button" (click)="SubmitData();" label="Save"></button>
</div>
x.component.ts:
uiData:any;
userData:any = null;
constructor() {
this.uiData = [
{ label:"test1",position: "left", control: "textbox",model: "userData.child1.docNumber" },
{ label:"test1",position: "left", control: "textbox", model: "userData.child1.wi"},
{ label:"test1",position: "right", control: "textbox", model: "userData.child1.nri" },
{ label:"test1",position: "left", control: "textbox", model: "userData.child1.dueDate" },
{ label:"test1",position: "left", control: "textbox",model: "userData.child1.initDate" },
]
}
SubmitData(){
console.log(this.userData);
}
导致:
答案 1 :(得分:0)
您必须实例化UserDataModel并设置[(ngModel)] =“ userData [ui.model]”