Angular2组件@Input双向绑定 [英] Angular2 Component @Input two way binding
问题描述
我有一个数据驱动的Angular应用程序.我有一个切换组件,该组件在切换状态下传递.我的问题是,除非我将toggle布尔值作为对象传递,否则双向数据绑定似乎无法正常工作.有没有一种方法可以使它不使用EventEmitter或将变量作为对象传递而工作.这将是一个可重用的组件,并且应用程序是由大量数据驱动的,因此不能将值作为对象传递.我的代码是....
I have a data driven Angular application. I have a toggle component which I pass in a toggled state. My issue is that the two way data binding does not seem to work unless i pass in the toggle boolean as an object. Is there a way to get this to work without using an EventEmitter or passing the variable in as an object. This is to be a reusable component and the application is heavily data driven so passing the value in as an object in not an option. My code is....
toggle.html
toggle.html
<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>
toggle.component.ts
toggle.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
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
之类的东西.这是一种语法约定.
[UPDATE] - 25 June 2019
From @Mitch's comment below:
It's worth noting that the @Output
name must be the same as the @Input
name, but with Change
on the end. You can't call it onToggle
or something. It's a syntax convention.
这篇关于Angular2组件@Input双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!