In this article, we will learn how to project content in an Angular Element. If you are unfamiliar with the following,
- Shadow Dom
- ViewEncapsulation
- Content Projection
I recommend you read the articles below before moving forward:
As of now, you know that we use ng-content to carry out content projection as shown in the next listing:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
@Component({ | |
selector: 'app-greet', | |
template: ` | |
<h2>{{title}}</h2> | |
<ng-content></ng-content> | |
` | |
}) | |
export class GreetComponent { | |
title = 'Greet'; | |
} |
You can also project content as shown in the next listing:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1> | |
Welcome to {{ title }}! | |
</h1> | |
<app-greet> | |
<h3>Hello Foo</h3> | |
</app-greet> |
The challenge with the above approach is, “If you use GreetComponent as your Angular Element,” you will not able to project content. To understand this better, let us start with converting GreetComponent to an Angular Element. Here you can Learn Step by Step tp Create Angular Element.
After converting GreetComponent as Angular Element, AppModule should look like the listing below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AppComponent } from './app.component'; | |
import { GreetComponent } from './greet.component'; | |
@NgModule({ | |
declarations: [ | |
AppComponent, GreetComponent | |
], | |
imports: [ | |
BrowserModule | |
], | |
providers: [], | |
bootstrap: [GreetComponent], | |
entryComponents: [GreetComponent] | |
}) | |
export class AppModule { | |
constructor(private injector: Injector) { | |
const customElement = createCustomElement(GreetComponent, { injector }); | |
customElements.define('app-root', customElement); | |
} | |
ngDoBootstrap() { | |
} | |
} |
Now you can use GreetComponent on index.html as shown in the listing below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<!– <app-root></app-root> –> | |
<app-greet> | |
<h2>hey Foo</h2> | |
</app-greet> | |
</body> |
Upon running the application, you will find that the <h2> element has not been projected to the Angular Element GreetComponent.
Leave a Reply