我有一个数据驱动的 Angular 应用程序。我有一个以切换状态传递的切换组件。我的问题是,除非我将切换 bool 值作为对象传递,否则双向数据绑定(bind)似乎不起作用。有没有办法让它工作而不使用 EventEmitter 或将变量作为对象传递。这是一个可重用的组件,并且应用程序是大量数据驱动的,因此不能将值作为对象传递。我的代码是....
切换.html
<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>
切换.component.ts
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'toggle-switch',
templateUrl: 'toggle-switch.component.html',
styleUrls: ['toggle-switch.component.css']
})
export class ToggleSwitchComponent {
@Input() toggleId: string;
@Input() toggled: boolean;
}
parent.component.html
<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>
最佳答案
要使 [(toggled)]="..."
正常工作,您需要
@Input() toggled: boolean;
@Output() toggledChange: EventEmitter<boolean> = new EventEmitter<boolean>();
changeValue() {
this.toggled = !(this.toggled);
this.toggledChange.emit(this.toggled);
}
[更新] - 2019 年 6 月 25 日
以下来自@Mitch 的评论:
值得注意的是,@Output
名称必须与@Input
名称相同,但要在末尾加上Change
。您不能将其称为 onToggle
或其他名称。这是一种语法约定。
关于Angular2 Component @Input 双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006770/