skip to Main Content

Is it possible to add the " *ngIf " directive to an element created with TypeScript?

The only solution that I found yet is, depending on the condition, this element dynamically created changes it’s display between ‘none’ or ‘block’.

Tried with ‘element.setAttribute()’ but doesn’t work.
Tried with creating an element and setting it’s ‘innerHTML’ like this:

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

Used the tag ‘child’ as a representation of a random element.
Also didn’t work.

Thanks in advance!

2

Answers


  1. You are already creating dynamic elements on certain condition then what is the exact usecase for adding *ngIf directive on those elements? It would be helful if you share insights on the use case.

    Ok Thanks for the use case.

    Can you check the below code:

    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);
      }
    }
    
    Login or Signup to reply.
  2. Your HTML string inside the innterHTML would not be parsed as the angular compiler only compiles templates at runtime when declared in the template property or external template file.

    You can try running your condition in your TS file.

    if(condition)
        element.innerHTML = `<child> ... </child>'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search