ng-content example | Angular

Last modified: July 2, 2019

my-button.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'my-button',
  template: `
    <button class='action-btn' (click)="action()">
      <ng-content></ng-content>
    </button>
  `
})

export class MyButtonComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  action(){
    console.log("action triggered")
  }
}

app.component.html

<my-button>
  Label 1
</my-button>

<my-button>
  Label 2
</my-button>

<ng-content> allows you to add dynamic content inside a custom component.

Using <ng-content>, we can create the same <my-button> with different labels.

<ng-content> helps us achieve translcusion in Angular.

ng-content example | multiple projections

contact.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'contact',
  styleUrls: ['./contact.component.css'],
  template: `
    <div class='contact'>
      <ng-content select="h1"></ng-content>
      <ng-content select=".phone"></ng-content>
      <ng-content></ng-content>
    </div>
  `
})
export class ContactComponent implements OnInit {
 constructor() { }
 ngOnInit() {
 }
}

app.component.html

<contact>
  <h1>John</h1>
  <span class="phone">555-433-3322</span>
  <p>John is a coworker.</p>
</contact>

<contact>
  <h1>Jim</h1>
  <span class="phone">555-334-1123</span>
  <p>Jim is a friend.</p>
</contact>

Using the select attribute, you can specify <ng-content> based on different selectors.

In this example, we specify an <ng-content> for h1 tags and another for elements with the phone class.

Also notice how we include a third <ng-content> without a select attribute. This functions as a "catch all" for any other content we include within our custom <contact> component that does not match the selectors.

ng-content example | styling projected content

contact.component.css

:host ::ng-deep .phone {
  color:red;
}

If you want to style the projected content within <ng-content>, you can do so using :host and ::ng-deep to apply styling to all nested elements within the <contact> component.

You might also like: