Angular2 组件@Input 双向绑定

问题描述 投票:0回答:2

我有一个数据驱动的 Angular 应用程序。我有一个切换组件,我以切换状态传递该组件。我的问题是,除非我将切换布尔值作为对象传递,否则两种方式的数据绑定似乎不起作用。有没有办法让它工作而不使用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>
angular typescript data-binding components decorator
2个回答
161
投票

为了

[(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
之类的。这是语法约定。


13
投票

虽然这个问题已有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"/>

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

© www.soinside.com 2019 - 2024. All rights reserved.