Sanjaya
Sanjaya

Reputation: 65

Add HTML elements into Angular Component

How to add a angular html element into a component in run time.

Let the html element is a H1 tag having angular expression.

<h1>{{testHeading}}</h1>

I want to insert this tag into a component. With persisting it's dynamic angular property. Here "testHeading" is a angular variable.

Am trying to add the element using the following method:

addComponent(component:any){
    let componentRef = this.componentFactoryResolver
    .resolveComponentFactory(component)
    .create(this.injector);

    this.appRef.attachView(componentRef.hostView);

    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
    .rootNodes[0] as HTMLElement;

    var newcontent = document.createElement('div');
    newcontent.innerHTML = `<h1>${this.demoText}</h1>`;
    domElem.appendChild(newcontent);

    document.getElementById("testid").appendChild(domElem);
}

Upvotes: 0

Views: 10068

Answers (1)

Felix Lemke
Felix Lemke

Reputation: 6488

Create a container in your template

<div #container></div>

Create a container reference by

@ViewChild('container') container: ElementRef;

And after view init you can access the container element for example by

container.nativeElement.innerHTML = `<h1>${yourString}</h1`;

Edit 2023: Updated ViewChild syntax

Upvotes: 2

Related Questions