![](/img/trans.png)
[英]Cannot read property of undefined @ViewChild not working Angular 5
[英]Angular bind ViewChild to Property in Class
我试图弄清楚如何将视图子项绑定到视图内部的类的子项组件。
我有一个模拟二进制表达式的模型:
export interface IODataExpression{
}
export class ODataExpressionDescriptor implements IODataExpression{
property: ODataProperty;
selectedFunction: ODataFunctionDescriptor;
value: any;
isNegated: boolean = false;
}
export class ODataBinaryExpressionDescriptor implements IODataExpression{
left: IODataExpression;
right: IODataExpression;
operator: ODataBinaryOperators;
}
我有一个看起来像这样的组件类:
binaryExpression: ODataBinaryExpressionDescriptor = new ODataBinaryExpressionDescriptor();
binaryOperatorKeys: any;
binaryOperators = ODataBinaryOperators;
@ViewChild('left') leftExpression: OdataSimpleFilterComponent;
left属性指向内部具有属性的组件:
odataExpression: ODataExpressionDescriptor = new ODataExpressionDescriptor();
我怎样才能使binaryExpression.left
始终等于子视图leftExpression.odataExpression
的视图?
使用一个EventEmitter
。
在OdataSimpleFilterComponent
@Output() odataExpressionChange = new EventEmitter<ODataExpressionDescriptor>();
然后,只要组件内部的值发生变化,您就可以执行以下操作:
this.odataExpressionChange.emit(this.odataExpression);
在主要组件中,您必须在ngAfterViewInit
(或ngAfterViewChecked
)中进行操作,以确保leftExpression
已初始化:
ngAfterViewInit() {
leftExpression.odataExpressionChange.subscribe(data => {
this.binaryExpression.left = data;
}
}
这样,无论EventEmitter
组件中的值发生变化,您都会收到一条通知(通过对EventEmitter
),并且可以做出相应的反应。
当然,某些细节可能会更改,因为我不知道您实现的所有细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.