Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 child component refers to parent component

Tags:

angular

I have an application which contains three components. Application, EditView,Dialog.

Application components contains EditView components which can contain many other EditView components and one Dialog component( if Dialog component is visible on a page).

Dialog component contains Application component. When I put that in Dialog component in declaration path:

directives:[Application]

I'am getting this error:

Unexpected directive value 'undefined' on the View of component 'Dialog'

Is it possible at all to have such structure where child component can contain component from upper level regarding some conditions?

If I drop Application component from Dialog or replace it with other components it works fine.

Zlaja

like image 613
zlaja Avatar asked Sep 21 '15 09:09

zlaja


People also ask

How to send data to parent using @viewchild in angular?

The Child can send data to Parent by raising an event, Parent can interact with the child via local variable or Parent can call @ViewChild on the child. We will look at all those options in this article. Applies to: Angular 2 to the latest edition of i.e. Angular 8.

What happens to the parent component when the child component starts?

5 At the time your ChildComponent (you called it also ParentComponent, but i guess it's a typo) gets initialized and executes its ngOnInit, there is no data in your parent avaible since your service will still be out getting your data. Once your data is there it will be pushed to the child.

Why can't I use local variables in parent component?

The parent component itself has no access to the child. You can’t use the local variable technique if an instance of the parent component class must read or write child component values or must call child component methods.

How does ngoninit work with childcomponent?

At the time your ChildComponent (you called it also ParentComponent, but i guess it's a typo) gets initialized and executes its ngOnInit, there is no data in your parent avaible since your service will still be out getting your data. Once your data is there it will be pushed to the child.


1 Answers

Putting it in the directives list won't work, but you can still have access to the parent component by having it injected in the constructor of the child directive:

constructor(@Host(Application) application: Application) {

}

And the parent component can get a live list of child components using @Query:

constructor(@Query(EditView) editViews: QueryList<EditView>){

}
like image 81
Angular University Avatar answered Oct 26 '22 08:10

Angular University