繁体   English   中英

Angular2 - 从子组件访问父组件的变量

[英]Angular2 - Accessing parent component's variable from child component

我想从子组件访问父组件上的变量,并使用它做一些事情。 这是我如何做到这一点,但看起来它不起作用,因为它假设:

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 对此有何解决方案?

似乎方法的范围不会以您传递的方式保留。

它作为闭合箭头函数传递时有效

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM