angular - Accessing a property in a parent Component in Angular2 with TypeScript -
i'm trying teach myself angular2 , typescript after happily working angular 1.* last 4 years! anyway, have property in top level component user data http source so... (this in file called app.ts
)
import {userdata} './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 userdata injectable service have written userstatus: userstatus; constructor(private userdata: userdata) { this.userstatus = new userstatus(); } ngoninit() { this.userdata.getuserstatus() .subscribe( (status) => { this.userstatus = status; // want access in child components... }, (err) => {console.log(err);}, () => {console.log("user status complete"); } ); } }
now have component direct child of top level component , within access parent's property 'userstatus
', here child...
component({ selector: 'profile', template: require('app/components/profile/profile.html'), providers: [], directives: [], pipes: [] }) export class profile implements oninit { constructor() { } ngoninit() { // want have access parent app component, 'userstatus' propety here... want read property } }
now in angular1.x easy reference $parent
in child controller or (anti pattern alert!!!) foolish put data in $rootscope
. best way access parent in angular2? in advance.
there different way:
global service
service shared parent , injected child
- similar global service listed in
providers
orviewproviders
in parent instead ofboostrap(...)
, available children of parent.
- similar global service listed in
parent injected child , accessed directly child
- disadvantage: tight coupling
export class profile implements oninit { constructor(@host() parent: app) { parent.userstatus ... }
- data-binding
export class profile implements oninit { @input() userstatus:userstatus; ... } <profile [userstatus]="userstatus">
Comments
Post a Comment