使用TypeScript访问Angular2中父组件中的属性

Mik*_*Sav 57 typescript angular

在过去的4年里,我正在努力与Angular 1.*一起工作,我正在尝试自学Angular2和TypeScript!无论如何,我在顶级组件中有一个属性,它是来自http源的用户数据,如此...(这是在一个名为的文件中app.ts)

import {UserData} from './services/user-data/UserData';

Component({
    selector: 'app', // <app></app>
    providers: [...FORM_PROVIDERS],
    directives: [...ROUTER_DIRECTIVES],
    pipes: [],
    template: require('./app.html')
})
@RouteConfig([
    // stuff here
])

export class App {
    // Please note that UserData is an Injectable Service I have written
    userStatus: UserStatus;

    constructor(private userData: UserData) {
        this.userStatus = new UserStatus();
    }

    ngOnInit() {
        this.userData.getUserStatus()
            .subscribe(
            (status) => {
                this.userStatus = status; // I want to access this in my Child Components...
            },
            (err) => {console.log(err);},
            () => {console.log("User status complete");            }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有另一个组件,它是顶级组件的直接子组件,在其中我想访问父组件的属性' userStatus',这里是孩子......

Component({
    selector: 'profile',
    template: require('app/components/profile/profile.html'),
    providers: [],
    directives: [],
    pipes: []
})

export class Profile implements OnInit {
    constructor() {

    }

    ngOnInit() {
        // I want to have access with the parent App Component, 'userStatus' propety here... I only want to read this property
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在Angular1.x中这很容易,因为我可以$parent在我的孩子控制器中引用或(反模式警告!!!)我可能很愚蠢地将这些数据放入我的$rootScope.在Angular2中访问父级的最佳方法是什么?提前致谢.

Gün*_*uer 64

有不同的方式:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
Run Code Online (Sandbox Code Playgroud)
  • 数据绑定
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">
Run Code Online (Sandbox Code Playgroud)

  • @GünterZöchbauer,我很高兴你指出了`@ Inputs`的"*缺点:紧耦合*",但我希望你承认使用服务的**缺点**,即与Angular的依赖注入系统的便利性有关.**读者应该知道,具有高*Link-Degree*即*Fan-Out/-In*同样危险**.通过直接输入链接,你至少遵守*LoD*(Demeter法则),但我会为每个*模块设计一个沙盒或导演/门面,这样他们就不会向多种服务扇出; 因为*那是*当你真的被冲洗的时候. (2认同)

mik*_*oft 31

我有同样的问题,但我解决了不同的问题.我不知道这是否是一种很好的方式,但它对我需要的东西很有用.

我在子组件的构造函数上使用了@Inject,如下所示:

import { Component, OnInit, Inject } from '@angular/core';
import { ParentComponent } from '../views/parent/parent.component';

export class ChildComponent{
    constructor(@Inject(ParentComponent) private parent: ParentComponent){

    }

    someMethod(){
        this.parent.aPublicProperty = 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我有用,你只需要声明你想要公开的方法或属性.

就我而言,AppComponent处理路由,我在菜单项中使用徽章来提醒用户新的未读消息可用.因此,每当用户阅读消息时,我希望该计数器刷新,因此我调用刷新方法,以便菜单导航中的数字使用新值更新.这可能不是最好的方式,但我喜欢它的简单性.

  • 这是一个很好的解决方法,但它不是一个解决方案,因为在大多数情况下,组件父级会随着您想要重用组件而变化。 (2认同)

Thi*_*ier 13

你可以:

  • 这对我来说没有多大意义。你的父类 Profile 有一个属性,然后你说你将它注入到你的子组件 Profile 中?!?!?看起来您正在将名为 userSatus 的绑定与具有配置文件选择器的组件进行绑定,但您正在将 App 类注入到名称为 Profile no bindings 的组件。根据您的描述,我想象您有一个父类(定义 userStatus 的类)和一个子类,该子类在其构造函数中设置本地值,并且您应该在构造函数中注入父类。是这样还是? (2认同)

Deu*_*unz 8

我制作了一个通用组件,我需要使用它来引用父级.这是我想出的:

在我的组件中,我创建了一个@Input:

@Input()
parent: any;
Run Code Online (Sandbox Code Playgroud)

然后在使用此组件的父级中:

<app-super-component [parent]="this"> </app-super-component>
Run Code Online (Sandbox Code Playgroud)

在超级组件中,我可以使用来自父组件的任何内容:

属性:

parent.anyAttribute
Run Code Online (Sandbox Code Playgroud)

功能 :

parent[myFunction](anyParameter)
Run Code Online (Sandbox Code Playgroud)