2016-02-29 104 views
3

我想從子組件訪問父組件的變量,並對其執行某些操作。這裏是我正在做它,但它看起來像它不工作,因爲它猜想:Angular2 - 從子組件訪問父組件的變量

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。任何解決方案?

回答

3

似乎該方法的範圍並不保留您傳遞它的方式。

它的工作原理,當作爲closureized箭頭功能

ngAfterViewInit(){ 
    this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => { 
     child.instance.log =() => this.callback(); 
    }); 
} 

https://plnkr.co/edit/VQ3c2Lv5KEzHUa2ZbGLk?p=preview

+0

過去了哇,這工作,但我不明白它是如何工作? – essaji

+1

'=>'像'.bind(this)'一樣工作。 '()=> this.callback()'使'this.callback()'執行'this'作爲'AppComponent'而沒有'this'就是'ChildComponent' –

+0

謝謝你man,你是一個救生員 – essaji