Angular-使用getters/setter方法将输入属性绑定到组件的两种方式 [英] Angular - Two way binding input property to component with getters / setters
问题描述
我有以下角度分量:
ComponentB
和在模板文件中插入 componentB
的 componentA
.该代码如下所示:
ComponentB
which has an input property, and componentA
which insert componentB
in the template file.
The code looks as the following:
componentA.ts:
componentA.ts:
export class ComponentA{
isOpen: boolean;
methodA() {
this.isOpen = false;
// do some work
}
}
componentA.html:
componentA.html:
<componentB [(open)]="isOpen"></componentB >
ComponentB.ts:
ComponentB.ts:
@Component({
selector: 'componentB',
templateUrl: 'ComponentB .html',
encapsulation: ViewEncapsulation.None,
})
export class ComponentB {
private _open: boolean = false;
@Input('open') set open(value: boolean) {
if (open === this._open) {
return;
}
if (open) {
// doSomething()
} else {
// doSomethingElse()
}
this._open = open;
}
get open() {
return this._open;
}
}
问题是,尽管指定了双向绑定,但 isOpen
属性似乎并未反映 open
属性的当前值.
The issue is that isOpen
property doesn't seems to reflect the current value of open
property, although two way binding was specified.
为什么会发生?怎么解决?
Why does it happens? How can it be fixed?
推荐答案
双向绑定是angular提供的一种特殊语法,用于设置组件的值和监听值的变化.
Two way binding is a special syntax that angular provides to set the value of a component and listen to value changes at the same time.
为此目的,特殊语法(方框中的香蕉)" [()] "用来.请在此处找到官方的角度文档.
For this purpose special syntax (Banana in a box) "[()]" is used. Please find the official angular documentation about this here.
简而言之,您将必须提供一个带有 @Input()装饰器的属性,以及一个带有 @Output()装饰器的属性.@Output()属性将在其后附加单词 Change .因此,如果@Input属性名称为 x ,则输出属性名称应为 xChange .只要更改了底层绑定属性,就使用输出属性的 EventEmitter ,让父组件侦听更改(因此实现了双向绑定).
In a nutshell, you'll have to provide one property with @Input() decorator, and one property with @Output() decorator. The @Output() property will have the word Change appended to it. So if the @Input property name was x then the output property name shall be xChange. And whenever the underlying bound property is changed, using the EventEmitter of the output property, let the parent component listen to the change (hence two way binding implemented).
在您的情况下,您的代码将像这样更新
In your case your code would update like this
@Input('open') set open(value: boolean) {
if (value === this._open) {
return;
}
if (open) {
// doSomething()
} else {
// doSomethingElse()
}
this._open = value;
this.openChange.emit(this._open); //open value set, the updated value is emitted using the output property.
}
get open() {
return this._open;
}
@Output('openChange') //the output property added
openChange = new EventEmitter<boolean>();
请找到 查看全文