如何将指令“*ngIf”添加到动态创建的元素中?

3

在使用TypeScript创建的元素中,是否可以添加“*ngIf”指令?

我目前找到的唯一解决方案是,根据条件动态更改此元素的显示方式,使其在“none”和“block”之间切换。

尝试使用“element.setAttribute()”,但无效。也尝试过创建一个元素并设置其“innerHTML”,如下所示:

element.innerHTML = `
<child *ngIf="condition"> ... </child>
`

使用'tag'标签作为随机元素的表示,但是没有起作用。

提前感谢!

2个回答

0

如果您已经根据某些条件创建了动态元素,那么在这些元素上添加*ngIf指令的确切用例是什么?如果您分享一些有关用例的见解,那将会很有帮助。

好的,谢谢您提供用例。

您能检查下面的代码吗:

import { Component, ViewChild, ViewContainerRef, Renderer2, ElementRef } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <div #container></div>
  `
})
export class ExampleComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngOnInit() {
    const div = this.renderer.createElement('div');
    const text = this.renderer.createText('This element is dynamically created');

    // Add ngIf directive to the element
    const ngIfAttribute = this.renderer.createAttribute('ngIf');
    this.renderer.setAttribute(ngIfAttribute, '', true);
    this.renderer.setAttribute(div, ngIfAttribute.name, ngIfAttribute.value);

    // Append text node to the div element
    this.renderer.appendChild(div, text);

    // Append div element to the container
    this.container.element.nativeElement.appendChild(div);
  }
}

没错,这就是为什么我选择在条件成立的情况下创建该元素的原因。在我的情况下,它是一个弹出消息。根据不同的情况,在这个弹窗里会有一个或另一个信息。这就是 *ngIf 指令发挥作用的时候。 - tobi
我添加了一个类似的用例。请检查并告诉我它是否有用。 - thilaga raj

0

你在innerHTML中的HTML字符串不会被解析,因为Angular编译器只在运行时编译在template属性或外部模板文件中声明的模板。

你可以尝试在TS文件中运行你的条件。

if(condition)
    element.innerHTML = `<child> ... </child>'

是的!那就是我使用的解决方案。不管怎样,我想知道是否有更好的解决方案。谢谢! - tobi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接