[英]Angular2 - Accessing parent component's variable from child component
我想從子組件訪問父組件上的變量,並使用它做一些事情。 這是我如何做到這一點,但看起來它不起作用,因為它假設:
parent.ts
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);
child.ts
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();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.