Content Projection in Angular Element with Slot in Angular 7.0

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:

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

view raw
debugmode1.js
hosted with ❤ by GitHub

You can also project content as shown in the next listing:

<h1>
Welcome to {{ title }}!
</h1>
<app-greet>
<h3>Hello Foo</h3>
</app-greet>

view raw
debugmode2.html
hosted with ❤ by GitHub

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:

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() {
}
}

view raw
debugmode3.js
hosted with ❤ by GitHub

Now you can use GreetComponent on index.html as shown in the listing below:

<body>
<!– <app-root></app-root> –>
<app-greet>
<h2>hey Foo</h2>
</app-greet>
</body>

view raw
debugmode4.html
hosted with ❤ by GitHub

Upon running the application, you will find that the <h2> element has not been projected to the Angular Element GreetComponent.

Read full article on the Infragistics blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s