从Victor Savkin在Angular2模板语法上的文章中,可以看到如何使用输入和输出属性绑定-
<todo-cmp [model]="todo" (complete)="onCompletingTodo(todo)"></todo-cmp>
@Component({selector: 'todo-cmp'})
class TodoCmp {
@Input() model;
@Output() complete = new EventEmitter(); // TypeScript supports initializing fields
}input属性使用@Input()修饰,而output属性具有@Output()。如何声明将具有双向属性绑定的属性?示例:假设rootpanel组件具有“建议”属性(类型为string),而searchPanel具有“getSuggestions属性”。现在,我希望这两个属性相互绑定。
rootpanel.html:
<search-panel [(getSuggestions)]="suggestions"> </search-panel>但是,在声明getSuggestions组件中的searchPanel属性时,我被困住了。另外,getSuggestions属性的类型应该是什么- string or EventEmitter<string>
请建议一下。
发布于 2016-01-15 11:16:10
如果希望从父组件绑定双向模型:
[(model)]在子组件中需要以下内容:
@Input() model: string;
@Output() modelChange:EventEmitter<string>;当模型在子组件中被覆盖时,您将发出modelChange事件:
updateModel(newValue:string) {
this.model = newValue;
this.modelChange.emit(this.model);
}从父组件的角度来看,[(model)]相当于:
[model]="model" (modelChange)="model=$event"这样,当模型属性在子组件中发生变化时,模型中的更改通过双向绑定向上传播,同步所有绑定的模型。
发布于 2016-01-15 11:17:06
如果要使用[(getSuggestions)]-style进行双向绑定,请声明以下字段
class TodoCmp {
@Input() getSuggestions;
@Output() getSuggestionsChange = new EventEmitter();
onClick() {
getSuggestions = 'someValue';
getSuggestionsChange.emit(getSuggestions);
}
}对于这样的输入/输出组合,getSuggestions可能不是一个很好的选择,但它应该演示它们是如何连接的。输出需要与具有附加Change的输入具有相同的名称。如果此命名方案不合适,请使用以下组件
<search-panel [suggestions]="suggestions" (getSuggestions)="updateSuggestions($event)> </search-panel>与输入/输出类似
class TodoCmp {
@Input() suggestions;
@Output() getSuggestions = new EventEmitter();
onClick() {
suggestions = 'someValue';
getSuggestions.emit(getSuggestions);
}
}发布于 2020-02-28 14:45:16
像素位推荐的方法是您应该如何做到这一点,但是如果组件上有多个双向数据绑定属性,甚至是代码库中经常更改的属性,我为此创建了一个装饰器。如果您正在使用npm 这里,则是。如果需要代码,只需转到gihub页面即可。
这样,您就可以直接使用:
import { Component } from '@angular/core';
import { TwoWay } from 'two-way-decorator';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class ExampleComponent {
@TwoWay()
public text: string;
@TwoWay()
public count: number;
}
https://stackoverflow.com/questions/34809699
复制相似问题