How to dynamically createelement with ngif in it

613 views Asked by At

I'm adding elements to the document and I'd like to add this one <button *ngIf="isPlaying()" (click)="backward15Sec()" class="control-btn backward-btn" [ngClass]="{'disabled':!isBackwardBtnEnabled()}"></button>

const btnElem = document.createElement("button");       
btnElem.className = "control-btn backward-btn";
btnElem.addEventListener('click', (e) => {
    this.backward15Sec();//your typescript function
});
document.getElementById("userDetails").appendChild(btnElem);
  1. How can I add the *ngIf= and [ngClass]= programmatically?
  2. Why when setting the class name programmatically the css style of the class name is not taking?
1

There are 1 answers

0
Andrei On

in the question code you are creating elements by yourself, without angular context or something simillar. you can't just apply directives to such elements. Instead you could track changes of you ended field and add/remove the element whenever you want

set ended(val) { 
  if(val) {
    this.reattachElement();
  } else {
    this.removeElement();
  }
}
elementToRender = ...; // your element will be here;
reattachElement() {
   document.getElementById("userDetails").appendChild(this.elementToRender);
}
removeElement() {
   this.elementToRender.remove();
}