When working with Angular, at times we find we need to render content, based on a given condition, but we wanna do it cleanly. This is where Angular NgContainer comes into the picture.
You are required to show either the use’r avatar or their initials, depending on whether they have an avatar on their account.
Component
When using Angular NgContainer, we will be importing a couple of things into our Angular standalone component, these are:
NgIf
NgTemplateOutlet
Like so:
@Component({
selector: 'app-angular-ng-container-tutorial',
standalone: true,
imports: [NgIf, NgTemplateOutlet],
templateUrl: './angular-ng-container-tutorial.component.html',
styleUrls: ['./angular-ng-container-tutorial.component.scss'],
})
export class AngularNgContainerTutorialComponent {
public myUser: {
fullname: string;
username: string;
avatar?: string;
initials?: string;
} = {
fullname: 'Binge On Code',
username: 'bingeoncode',
};
ngOnInit(): void {
this.myUser.initials = this.myUser.fullname
.split(' ')
.map((part) => part[0].toUpperCase())
.join('');
}
}
HTML
Now, this is how we will change our HTML to look like.
<div class="wrapper">
<ng-container
*ngTemplateOutlet="myUser.avatar ? avatarTemplate : initialsTemplate"
></ng-container>
<ng-template #avatarTemplate>{{ myUser.avatar }}</ng-template>
<ng-template #initialsTemplate>{{ myUser.initials }}</ng-template>
</div>
The first thing to note is that we are using *ngTemplate as the directive, which decides which NgTemplate we need to render, like so
<ng-container
*ngTemplateOutlet="myUser.avatar ? avatarTemplate : initialsTemplate"
></ng-container>
So, whenever we have an avatar, then the avatar template will be rendered, else the initial template will be rendered.
And that is it! It is this simple, the best part is that you can scale this simple Angular NgContainer tutorial into having even nested structures.
Have a condition.
Display a NgTemplate based on the condition.
Render what is needed on the right template.
And with that, happy coding!