Codehan25
Codehan25

Reputation: 3014

How to use ng-container and ng-template

I would like to provide another logo if a *ngIf returns true.

For this I have created a ng-template and want to display it within an ng-container.

Unfortunately, I can not get it right now. What am I doing wrong?

Here is my ng-template:

<ng-template *ngIf="customLogo" #customHeader>
  <ng-container *myHeader>
      <img src="{{customSrc}}}" alt="..." class="">
  </ng-container>
</ng-template>

And here I want to use it:

<nav *navItems>
  <ng-container *ngTemplateOutlet="customHeader"></ng-container>
  <ng-container *ngFor="let bc of bcases">
      // Some other stuff..
  </ng-container>
</nav>

Upvotes: 0

Views: 4070

Answers (2)

Saravanan S
Saravanan S

Reputation: 133

A Short description & Simple example for ng-container and ng-template.

ng-containers If you're familiar with React, you may know the Fragment React component. This component is used when you do not want to add an extra HTML element to the DOM (like a div or span), but you want a wrapper around children components. It work just like that, and it also accepts Angular structural directives (ngIf, ngFor, e.t.c). They are elements that can serve as wrappers but do not add an extra element to the DOM.

ng-template as a template that defines a composition of elements (the template content), but Angular does not render it by default. It only does when you specify it to be rendered.

products.component.html

 <ng-container *ngIf="products.length > 0; else noProducts">
  <ng-container *ngFor="let product of products">
    <div *ngIf="product.id">
      <span>{{ product.name }}</span>
    </div>
  </ng-container>
</ng-container>

<ng-template #noProducts>
  <p>There are no products in this store</p>
</ng-template>

products.component.ts

import { Component, OnInit, VERSION } from '@angular/core';

interface Fruit {
  id: String;
  name: String;
}
@Component({
  selector: 'my-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductComponent implements OnInit {
  public products: Array<Fruit> = [
    {
      id: '1',
      name: 'apple',
    },
    {
      id: '2',
      name: 'banana',
    },
    {
      id: '3',
      name: 'pine apple',
    },
    {
      id: '4',
      name: 'jerry',
    },
  ];

  constructor() {
    // console.log('constructor');
  }

 
  ngOnInit() {
    console.log('ngOnInit');
    // this.products = [];
  }
}

Upvotes: 0

Codehan25
Codehan25

Reputation: 3014

I just found out that I can not nest an ng-container inside an ng-template.

I solved it this way:

  <ng-container *ngIf="customLogo">
    <ng-container *myHeader>
      <img src="{{customLogoSrc}}" alt="" class="">
    </ng-container>
  </ng-container> 

Upvotes: 1

Related Questions