Mike Sav February 2016

Accessing a property in a parent Component in Angular2 with TypeScript

I'm currently trying to teach myself Angular2 and TypeScript after happily working with Angular 1.* for the last 4 years! Anyway, I have a property in a top level Component that is user data from a http source like so... (this is in a file called 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");            }
        );
    }
}

Now I have another Component that is a direct child of the top level Component and within it I would like to access the parent's property 'userStatus', here is the child...

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
    }
}

Now in Angular1.x this would be easy as I could reference $parent in my child controller or (ANTI PATTERN ALERT!!!) I could be so foolish to put this data in my $rootScope. What would be the best way

Answers


Günter Zöchbauer February 2016

There are different way:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
  • data-binding
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<provile [userStatus]="userStatus>


Thierry Templier February 2016

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

Post Status

Asked in February 2016
Viewed 1,347 times
Voted 5
Answered 2 times

Search




Leave an answer