【发布时间】:2016-02-29 05:14:32
【问题描述】:
我想从子组件访问父组件上的一个变量并用它做一些事情。这是我的做法,但它看起来不像它想象的那样工作:
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。有什么解决办法吗?
【问题讨论】:
标签: javascript angular