angularangular-directivecustom-directive

Custom Structural Directive to Conditionally Render a Component or Element


In angular 15, I'm making a custom directive to show or hide an element/component conditionally, i've simplified the example by setting true/false explicitly but setting ngIf to true or false isn't working. Any ideas why and how to fix it?"

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

import { NgIf } from '@angular/common';
import { Directive, OnInit, inject } from '@angular/core';

@Directive({
  selector: '[appMyIf]',
  hostDirectives: [NgIf],
  standalone: true,
})
export class MyIfDirective implements OnInit {
  private readonly ngIfDirective = inject(NgIf);

  constructor() {}

  ngOnInit(): void {
    this.ngIfDirective.ngIf = true;
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1 *appMyIf>Hello from {{ name }}!</h1>
    <a target="_blank" href="https://angular.dev/overview">
      Learn more about Angular
    </a>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

Solution

  • Remember to import your directive in the component where it is used:

    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [MyIfDirective],    // ADD THIS LINE
      template: `
      <h1 *appMyIf>Hello from {{ name }}!</h1>
      <a target="_blank" href="https://angular.dev/overview">
          Learn more about Angular
        </a>
      `,
    })
    export class App {
      name = 'Angular';
    }
    

    Stackblitz: https://stackblitz.com/edit/stackblitz-starters-1sojwq?file=src%2Fmain.ts