trance_dude
trance_dude

Reputation: 101

Angular: parent and child component communication, @Host and forwardRef

I am experimenting with the newly released Angular beta 0 and hoping someone can clarify some things for me.

I have an AppComponent which is serving as the main framework of my project. Its template creates a navigation bar, the items of which are read into a public variable (call it "items") of AppComponent upon its ngOnInit. *ngfor then renders the items. This is working fine.

At the bottom of the AppComponent template is a div in which a router-outlet is placed. Depending on which navigation item the user selects a route is triggered and a different sub-component is rendered. This also works fine. In one of these sub-components I need to refer to the variable "items" in the parent AppComponent. I tried three ways of passing the AppComponent to the SubComponent in its constructor:

1. constructor(@Host() _host: AppComponent)
2. constructor(@Inject(forwardRef(() => AppComponent)) _host)
3. constructor(@Host() @Inject(forwardRef(() => AppComponent)) _host)

Method 1 fails at runtime with an error like "Cannot resolve all parameters for SubComponent", while methods 2 and 3 work, but I don't understand why. It would lead one to believe that AppComponent is undefined when the constructor of SubComponent is called, which is impossible, because SubComponent cannot exist unless it's rendered in the router-outlet of AppComponent's template. But the forward reference does work.

I can post more code but I think I am missing something conceptual here?

Side question - I see in previous alpha releases that the decorator @View was often used in component definitions, e.g. to specify the template. In all of the examples currently on the Angular website I never see @View but only the @Component decorator. Is @View now obsolete?

Upvotes: 1

Views: 3519

Answers (1)

user2499264
user2499264

Reputation: 11

To your side question: @View is now optional (if it's not there, then you need 'templateURL' or 'template' set in your @Component) - This change was made in the 2.0.0-alpha.40 release (https://github.com/angular/angular/blob/master/CHANGELOG.md#200-alpha40-2015-10-09)

Upvotes: 1

Related Questions