0

I have a unordered <ul> list element that I want to add items to from my Javascript. Just small, simple snippets such as <li>Label: Text</li>.

I could use the ViewContainerRef.createComponent(ItemComponent) and create a new component for a list item, but I feel that is so overkill when I just want to insert such a simple snippet of HTML to the DOM.

What's the best way to add these type of simple, short HTML snippets to the DOM when it does not require a full component?

2 Answers 2

4
myHtml = '<li>Label: Text>/li>
<div [innerHTML]="myHtml">

the added myHtml string won't be processed by Angular in any way (no bindings, no components, directives, ...)

See also angular 2 html binding

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

Comments

-1

You don't need Angular to do this.

function addItem() {
  document.getElementById("list").innerHTML += "<li>Item 3</li>";
}
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick="addItem()">Add item</button>

8 Comments

How can I get document in Angular?
@RomanC document is a native feature of JavaScript. As far as I know, Angular integrates with JavaScript. Also, the question is tagged JavaScript.
It doesn't work in typscript, could you create a plunker?
It's not my problem, but OP's problem, and your answer is wrong that's all.
@RomanC Quoting from the OP, I have a unordered <ul> list element that I want to add items to from my Javascript. Emphasis on the Javascript. I don't know why you edited in the tag TypeScript, this question is nothing of the sort.
|

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.