Angular2组件@Input双向绑定

Ste*_*ons 45 data-binding components decorator typescript angular

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

toggle.html

<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>
Run Code Online (Sandbox Code Playgroud)

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;

}
Run Code Online (Sandbox Code Playgroud)

parent.component.html

<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 75

为了[(toggled)]="..."你需要的工作

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

  changeValue() {
    this.toggled = !(this.toggled); 
    this.toggledChange.emit(this.toggled);
  }
Run Code Online (Sandbox Code Playgroud)

另请参见双向绑定

  • 值得注意的是,`@ Output`名称必须与`@ Input`名称相同,但最后使用`Change`.你不能称它为"onToggle"或其他东西.这是一种语法约定. (20认同)
  • @silentsod尽管如此,Angular还没有内置的方法来处理一个属性的双向绑定.看起来像一个超级基本功能; 然而,它根本不受支持.此外,Angular文档令人难以置信,难以理解,因此如果OP在阅读之后不理解如何做到这一点,我也不会感到惊讶. (11认同)
  • @ProxyTech,它记录在此处:https://angular.io/guide/two-way-binding:`当元素具有名为 x 的可设置属性和名为 xChange 的相应事件时,[()] 语法很容易演示。 。不过我同意应该强调这一点。 (2认同)

man*_*iti 12

虽然这个问题已经超过 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"/>
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以修改所有对象属性,并在两个组件中获得相同的值,因为它们共享相同的引用。