Skip to main content

Structural Directives - The Asterisk (*) Prefix

The (*) is a syntactic sugar. You'll have a ng-template wrapped arround the host element with the *directive.

This snippet

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: []
})
export class AppComponent {
  la = [1, 2, 3];
}

app.component.html

<div *bla="la">
  some content
</div>

will be transformed into

<ng-template [bla]="la">
	<div>
    	some content
    </div>
</ng-template>
  • The bla directive moved to ng-template element where it is now a property binding
    • meaning the BlaDirective should have an @Input() bla which will get the value of la.
  • The div element who hosted the *directive moved inside the ng-template.

and you need the directive like this

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[bla]'
})
export class BlaDirective {

  @Input() set bla(value) {
    console.log(value);
  }
  
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }
}

Structural directives need TemplateRef and ViewContainer.

TODO display the content of the template