我想从子组件访问父组件上的变量并对其进行处理。这是我的操作方式,但似乎无法正常工作:
父母
import {Component,DynamicComponentLoader,ElementRef,AfterViewInit} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChildComponent} from './child.ts';
@Component({
selector: 'app',
template: `<div #child></div>`
})
class AppComponent implements AfterViewInit{
public parentValue = "some value."
constructor(private _loader:DynamicComponentLoader,private _elementRef:ElementRef) {}
ngAfterViewInit(){
this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
child.instance.log = this.callback;
});
}
callback(){
console.log(this.parentValue); //logs undefined rather than "some value"
}
}
bootstrap(AppComponent);
孩子
import {Component} from 'angular2/core';
@Component({
selector: "child-component",
template: "<button (click)='logParentValue()' >Log Value</button>"
})
export class ChildComponent{
log:any;
logParentValue(){
this.log();
}
};
当我尝试从子组件中记录父组件变量的值时,它始终会记录undefined
。有什么解决办法吗?
似乎该方法的范围并未保留您传递它的方式。
作为封闭的箭头函数传递时可以使用
ngAfterViewInit(){
this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
child.instance.log = () => this.callback();
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句