访问父组件中的属性

新手上路,请多包涵

我在顶级组件中有一个属性,它使用来自 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");            }
        );
    }
}

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

现在在 Angular 1.x 中这很容易,因为我可以在我的子控制器中引用 $parent 或( ANTI PATTERN ALERT!!! )我可能很愚蠢地将这些数据放入我的 $rootScope .

在 Angular 2 中访问父级的最佳方式是什么?

原文由 Mike Sav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 843
2 个回答

有不同的方式:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}

  • 数据绑定
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

您还可以在属性名称之前添加 static 例如 - static myVariable = 5 并在子组件中导入父组件,然后使用 parentcomponent.myVariable 访问它;静态方法将使该属性在组件外部可用。

原文由 raj dubey 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进