Angular2组件@Input双向绑定

时间:2017-02-02 15:58:05

标签: angular typescript data-binding components decorator

我有一个数据驱动的Angular应用程序。我有一个切换组件,我以切换状态传递。我的问题是双向数据绑定似乎不起作用,除非我将toggle布尔值作为对象传递。有没有办法让它工作而不使用EventEmitter或将变量作为对象传递。这是一个可重用的组件,应用程序是大量数据驱动的,因此将值作为对象传递给非选项。我的代码是......

toggle.html

<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;

}

parent.component.html

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

2 个答案:

答案 0 :(得分:59)

[(toggled)]="..."工作,您需要

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

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

另见Two-way binding

答案 1 :(得分:4)

尽管问题已经超过2年,但我还是想捐5美分...

关于Angular并不是问题,关于Javascript的工作方式...简单的变量(数字,字符串,布尔值等)通过值传递,而复杂的变量(对象,数组)通过引用传递:

您可以在Kyle Simpson的系列文章中了解更多相关内容,您可能不了解js:

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

因此,您可以使用@Input()对象变量在组件之间共享作用域,而无需使用发射器,观察器等。

// 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"/>

这样,您可以修改所有对象的属性,并且由于它们共享相同的引用,因此在两个组件中获得相同的值。