首页 文章

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

提问于
浏览
45

在过去的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");            }
        );
    }
}

现在我有另一个组件,它是顶级组件的直接子组件,在其中我想访问父组件's property ' 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
    }
}

现在在Angular1.x中这很简单,因为我可以在我的子控制器中引用 $parent 或( ANTI PATTERN ALERT!!! )我可能很愚蠢地把这些数据放在我的 $rootScope 中 . 在Angular2中访问父级的最佳方法是什么?提前致谢 .

5 回答

  • 50

    有不同的方式:

    由父母共享的

    • 服务并注入给孩子

    • 类似于 global service ,但在父代的 providersviewProviders 中列出,而不是 boostrap(...) ,仅适用于父级的子级 .

    • 父母注入孩子并由孩子直接访问

    • 缺点:紧耦合

    export class Profile implements OnInit {
    constructor(@Host() parent: App) {
      parent.userStatus ...
    }
    
    • 数据绑定
    export class Profile implements OnInit {
      @Input() userStatus:UserStatus;
      ...
    }
    
    <profile [userStatus]="userStatus">
    
  • 17

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

    我在子组件的构造函数上使用了@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;
        }
    }
    

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

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

  • 13

    你可以:

    • 为子组件定义 userStatus 参数,并在父组件中使用此组件时提供值:
    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    在父母:

    <profile [userStatus]="userStatus"></profile>
    
    • 将父级注入子组件:
    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    注意它们之间的循环依赖关系 .

  • 5

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

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

    @Input()
    parent: any;
    

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

    <app-super-component [parent]="this"> </app-super-component>
    

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

    属性:

    parent.anyAttribute
    

    功能 :

    parent[myFunction](anyParameter)
    
  • 0

    在Angular 6上,我通过构造函数注入父访问父属性 . 不是最好的解决方案,但它有效:

    constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
        // And access like this:
        parentComponentInjectionObject.thePropertyYouWantToAccess;
    }
    

相关问题