0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

10 Comments

Great solution my dear bro, It's working fine. But I've one doubt what is the ${yourString}. I have never use a expression like this, I always use {{yourString}}. Could you please explain this or share a ref link where I'll get know about ${yourString} method.
You're welcome :) since it seems you are new to SO: If solutions are working for you, you should except the related answers as well.
{{yourString}} is interpolation in .html. ${yourString} is interpolation in .ts.
@HarunurRashid this actually is the .ts file.
@ngfelixl, One more thing in the expression ${yourString}` if I need to declare the variable 'yourString' in the child component where I need insert the HTML element (<h1>).Then it will showing error that 'yourString' is not defined, in the parent component. Is there any solution for this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.