Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 241
Eesa Avatar asked Dec 01 '25 09:12

Eesa


1 Answers

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

like image 149
Günter Zöchbauer Avatar answered Dec 03 '25 23:12

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!