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)
另请参见双向绑定
man*_*iti 12
虽然这个问题已经超过 2 年了,但我想贡献我的 5 美分......
这不是关于 Angular 的问题,它是关于 Javascript 如何工作的……简单变量(数字、字符串、布尔值等)按值传递,而复杂变量(对象、数组)按引用传递:
你可以在 Kyle Simpson 的系列你不知道 js 中阅读更多关于这个的信息:
因此,您可以使用 @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)
通过这种方式,您可以修改所有对象属性,并在两个组件中获得相同的值,因为它们共享相同的引用。
归档时间: |
|
查看次数: |
24342 次 |
最近记录: |