1
votes

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?

1
@View() is for future support of multiple views for one component. Until this is fully supported you can just use @Component(). If you plan to use this feature anyway, it might make sense to already use the @View() annotation.Günter Zöchbauer
Thanks for the link and answer on @View(). The link references another post github.com/angular/angular/issues/3216, the last comment of which explains that the module loader may leave "circular module dependencies ... uninitialized within one of the module". I still don't really understand how, in the course of running my particular app, the loader would or even could choose to load a version of my SubComponent that is not aware of the AppComponent module, given that an instance of the latter already actually exists. Anyway, forwardRef does work so I'll just stick with it. Thx!trance_dude
There was an acknowledgment that there is a bug even though the issue wasn't reopened yet.Günter Zöchbauer

1 Answers

1
votes

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)