简体   繁体   中英

How to dynamically createelement with ngif in it

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM