有条件地渲染组件或元素的自定义结构指令

问题描述 投票:0回答:1

在 Angular 15 中,我正在制作一个自定义指令来有条件地显示或隐藏元素/组件,我通过显式设置 true/false 简化了示例,但将 ngIf 设置为 true 或 false 不起作用。有什么想法以及如何解决它吗?”

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);
angular angular-directive custom-directive
1个回答
0
投票

记住将指令导入到使用它的组件中:

@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

© www.soinside.com 2019 - 2024. All rights reserved.