Angular2 Component@Input 双向绑定

我有一个数据驱动的角度应用程序。我有一个切换组件,我通过一个切换状态。我的问题是,双向数据绑定似乎不工作,除非我传递切换布尔作为一个对象。有没有办法让这个工作 而不使用 EventEmitter 或将变量作为对象传入。这是一个可重用的组件,并且应用程序是高度数据驱动的,因此将值作为对象传递给应用程序是不可选的。我的原则是..。

开关

<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>

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;


}

组件

<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>
61756 次浏览

For [(toggled)]="..." to work you need

  @Input() toggled: boolean;
@Output() toggledChange: EventEmitter<boolean> = new EventEmitter<boolean>();


changeValue() {
this.toggled = !(this.toggled);
this.toggledChange.emit(this.toggled);
}

See also Two-way binding

[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.

Although the question has more than 2 years old I want to contribute my 5 cents...

It isn't a problem about Angular, its about how Javascript works... Simple variables (number, string, boolean, etc) are passed by value whereas complex ones (objects, arrays) are passed by reference:

You can read more about this in Kyle Simpson´s series You dont know js:

https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch2.md#value-vs-reference

So, you can use an @Input() object variable to share scope between components without need to use emitters, observers and whatever similar.

// In toggle component you define your Input as an config object
@Input() vm: Object = {};


// In the Component that uses toggle componet you pass an object where you define all needed needed variables as properties from that object:
config: Object = {
model: 'whateverValue',
id: 'whateverId'
};


<input type="checkbox" [vm]="config" name="check"/>

This way you can modify all object properties and you get same value in both components because they share same reference.