Reputation: 1553
I was trying to learn how does two or more component communicate to each other in angular. hence after created an Angular project, I just created four new component named one, two, three and four.
After that, I was trying to add this code in app.component.html
<app-one>
<app-two>
<app-three> </app-three>
</app-two>
<app-four> </app-four>
</app-one>
All the component has the same class as below :
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-one-child',
templateUrl: './one-child.component.html',
styleUrls: ['./one-child.component.css']
})
export class OneChildComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
by doing so I thought One will be the parent component of all of them and all will render. But unfortunately, I got only
one works!
while other components do not render at all. I am sure I am having some serious problem with angular and how it works. Can you please explain why it's not rendering the data from two, three and four? if I want to let them work what should I do?
Upvotes: 0
Views: 2493
Reputation: 2452
If you need nested component, use ng-content
in the parent ones, e.g.
@Component({
selector: 'root',
template: '<div>I'm root, <ng-content></ng-content></div>'
})
export class RootComponent{}
@Component({
selector: 'child',
template: '<root>I'm children in the root</root>'
})
export class ChildComponent{}
and so on..
Then in your template, you can write:
<child></child>
It'll render I'm root, I'm children in the root
Or
<root>Hello world!</root>
It'll render I'm root, Hello World!
Here is a great article about using ng-content (transclusion)
Upvotes: 3
Reputation: 62238
Ideally each components template is responsible for its own html. IMO this would be the best way handle this.
See stackblitz
template for root component
@Component({
selector: '',
template: '<app-one></app-one>'
})
export class RootComponent{}
template for component 1
@Component({
selector: 'app-one',
template: '<app-two></app-two><app-four></app-four>'
})
export class Child1Component{}
template for component 2
@Component({
selector: 'app-two',
template: '<app-three></app-three>'
})
export class Child2Component{}
template for component 3
@Component({
selector: 'app-three',
template: '<h1>Hi there from 3</h1>'
})
export class Child3Component{}
template for component 4
@Component({
selector: 'app-four',
template: '<h1>Hi there from 4</h1>'
})
export class Child4Component{}
Upvotes: 3