Mayur Kukadiya
Mayur Kukadiya

Reputation: 2747

How can I add one component into another component using selector in angular?

In angular, there is one feature available that we can create a component once and then reuse it anywhere in the project.

I am working on one complex project where lot's of components are available. and now I want to make all these components more reusable.

That's why, I want to reuse my layout in the following way :

<car-layout [color]="'red'">
  <steering [color]="'black'"></steering >
  <rear-view-mirror [size]= "'12'"></rear-view-mirror>
</car-layout>

But I don't know how can it work ! If anyone know about it then please guide me for this...

Upvotes: 2

Views: 10073

Answers (2)

StefanK
StefanK

Reputation: 117

Within a component, you can use Content Projection to define a placeholder using the <ng-content></ng-content> tag.

In your example, you can use the <ng-content></ng-content>-tag within the HTML of your car-layout component. It will then be replaced by arbitrary content you are nesting within your car-layout component. For example

<car-layout>
  <p>Any HTML content</p>
</car-layout>

will project <p>Any HTML content</p> into your car-layout component and replaces the <ng-content></ng-content>-tag. Instead of the predefined paragraph p, you can also project your own components into the car-layout component:

<car-layout>
  <steering [color]="'black'"></steering >
  <rear-view-mirror [size]= "'12'"></rear-view-mirror>
</car-layout>

If one selector to project your content is not enough, you can also define multiple slots with Targeted Projection.

For more detailed information, look e.g. here or here.

Upvotes: 1

Nitin Lawande
Nitin Lawande

Reputation: 613

if you want to insert HTML elements or other components in a component, then you do that using the concept of content projection. In Angular, you achieve content projection using < ng-content >< /ng-content >. You can make reusable components and scalable applications by properly using content projection.

lets create one component i.e. GreetComponent.ts

 import { Component } from '@angular/core';
 @Component({
     selector: 'greet',
     template: `<div class="container">
                 <ng-content> </ng-content>
             </div>`
 })
 export class GreetComponent{ }

AppComponent.ts

      import { Component } from '@angular/core';
 @Component({
     selector: 'App',
     template: `<greet>
                    <h1>Hello World!!!!</h1> 
               </greet>`
 })
 export class AppComponent{ }

Content projection is very useful to insert shadow DOM in your components. To insert HTML elements or other components in a component, you need to use content projection.

Upvotes: 4

Related Questions