Angular2 - 在两个 [(ngModel)] 绑定之间共享布尔引用
Angular2 - Sharing Boolean Reference between two [(ngModel)] bindings
我正在开发一种所见即所得的表单创建器。我正在尝试通过选择要编辑的行并列出来自不同组件中的对象的键来使行可编辑。
组件A.ts
onedit() {
this.service.emit(this.rowConfig)
}
组件B.ts
ngOnInit() {
this.service.subscribe({
next: config => {
this.data = config
this.props = Object
.keys(config)
.reduce(/* convert to { key, inputType } */)
})
}
组件B.html
<div *ngFor="let prop of props">
<label>{{prop.key}}</label>
<input [type]="prop.inputType" [(ngModel)]="data[prop.key]" />
</div>
这适用于我尝试过的几种输入类型(文本、数字),但不适用于 "checkbox"。我什至向 props 实体添加了一个 ID
并将 id
和 name
属性添加到 <input [type]="prop.inputType" [id]="prop.ID" [name]="prop.ID" [(ngModel)]="data[prop.key]" />
布尔值的引用是否在某处丢失了?当共享对象的引用时,为什么双向绑定不适用于复选框(它适用于字符串和数字)?
这里唯一的问题是 [type]="prop.inputType"
,因为动态输入类型复选框不起作用
我已经找到了解决方法:
<input *ngIf='prop.inputType !== "checkbox"' [type]="prop.inputType" [name]='prop.name' [(ngModel)]="data[prop.key]" />
<input *ngIf='prop.inputType === "checkbox"' type='checkbox' [name]='prop.name' [(ngModel)]="data[prop.key]" />
我正在开发一种所见即所得的表单创建器。我正在尝试通过选择要编辑的行并列出来自不同组件中的对象的键来使行可编辑。
组件A.ts
onedit() {
this.service.emit(this.rowConfig)
}
组件B.ts
ngOnInit() {
this.service.subscribe({
next: config => {
this.data = config
this.props = Object
.keys(config)
.reduce(/* convert to { key, inputType } */)
})
}
组件B.html
<div *ngFor="let prop of props">
<label>{{prop.key}}</label>
<input [type]="prop.inputType" [(ngModel)]="data[prop.key]" />
</div>
这适用于我尝试过的几种输入类型(文本、数字),但不适用于 "checkbox"。我什至向 props 实体添加了一个 ID
并将 id
和 name
属性添加到 <input [type]="prop.inputType" [id]="prop.ID" [name]="prop.ID" [(ngModel)]="data[prop.key]" />
布尔值的引用是否在某处丢失了?当共享对象的引用时,为什么双向绑定不适用于复选框(它适用于字符串和数字)?
这里唯一的问题是 [type]="prop.inputType"
,因为动态输入类型复选框不起作用
我已经找到了解决方法:
<input *ngIf='prop.inputType !== "checkbox"' [type]="prop.inputType" [name]='prop.name' [(ngModel)]="data[prop.key]" />
<input *ngIf='prop.inputType === "checkbox"' type='checkbox' [name]='prop.name' [(ngModel)]="data[prop.key]" />