Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a component inside another component in Angular2?

I'm new at Angular and I'm still trying to understand it. I've followed the course on the Microsoft Virtual Academy and it was great, but I found a little discrepancy between what they said and how my code behave! Specifically, I've tried to "put a component inside another component" like this:

@Component({     selector: 'parent',     directives: [ChildComponent],     template: `             <h1>Parent Component</h1>             <child></child>         `     })     export class ParentComponent{}   @Component({     selector: 'child',         template: `             <h4>Child Component</h4>         `     })     export class ChildComponent{} 

This is the same example that they make on the course, but in my code doesn't work! In particular VisualStudio says to me that the 'directives' property doesn't exist in the component decorator. How can I solve this?

like image 808
Paolo Ardissone Avatar asked Apr 19 '17 10:04

Paolo Ardissone


People also ask

Can components be used inside other components?

By declaring a component inside another component, you are not only re-rendering both components, but completely redeclaring one. This won't be very performant, especially if the component is more complex. So the answer to your question is always declare it separate.


1 Answers

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({   imports: [ BrowserModule ],   declarations: [ App , MyChildComponent ],   bootstrap: [ App ] }) 

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

like image 126
Royi Namir Avatar answered Sep 19 '22 09:09

Royi Namir