3

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Wow that worked but I don't get it how is it working?
The => works like .bind(this). () => this.callback() makes this.callback() execute with this being AppComponent while without it this is ChildComponent
Your solution worked but it produced another problem now I am not able to pass argument to the parent in the callback. Any argument passed to the log function from child is undefined in parent. Why is that so?
You can change the signature like (x) => this.callback(x);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.