【问题标题】:Angular2 - Accessing parent component's variable from child componentAngular2 - 从子组件访问父组件的变量
【发布时间】:2016-02-29 05:14:32
【问题描述】:

我想从子组件访问父组件上的一个变量并用它做一些事情。这是我的做法,但它看起来不像它想象的那样工作:

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。有什么解决办法吗?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    方法的范围似乎没有按照您传递它的方式保留。

    当作为闭包箭头函数传递时它可以工作

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

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

    【讨论】:

    • 哇,好用,但我不明白它是如何工作的?
    • =&gt; 的工作方式类似于 .bind(this)() =&gt; this.callback() 使 this.callback() 执行时 thisAppComponent 而没有它 thisChildComponent
    • 您的解决方案有效,但它产生了另一个问题,现在我无法在回调中将参数传递给父级。从 child 传递给 log 函数的任何参数在 parent 中都是 undefined。为什么会这样?
    • 您可以更改签名,如(x) =&gt; this.callback(x);
    猜你喜欢
    • 2016-03-16
    • 2017-11-04
    • 1970-01-01
    • 2016-02-02
    • 2016-05-29
    • 2018-06-13
    • 1970-01-01
    • 2016-09-16
    • 2018-02-27
    相关资源
    最近更新 更多