gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:27:05 26 4
gpt4 key购买 nike

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

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

关于javascript - Angular2 - 从子组件访问父组件的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35692392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com