Eesa
Eesa

Reputation: 2859

Angular2 - Accessing parent component's variable from child component

I want to access a variable on the parent component from the child component and do something with it. Here is how I am doing it but it looks like its not working as it suppose to:

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();
    }
};

When I try to log the value of parent component's variable from the child component it always logs undefined. Any solution to this?

Upvotes: 3

Views: 1428

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658235

It seems the scope of the method is not preserved the way you pass it.

It works when passed as closureized arrow function

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

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

Upvotes: 3

Related Questions