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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Marcus Lind
  • 10,374
  • 7
  • 58
  • 112

2 Answers2

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
-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>
Okx
  • 353
  • 3
  • 23
  • How can I get `document` in Angular? – Roman C Jun 19 '17 at 12:54
  • 1
    @RomanC `document` is a native feature of JavaScript. As far as I know, Angular integrates with JavaScript. Also, the question is tagged JavaScript. – Okx Jun 19 '17 at 12:55
  • It doesn't work in typscript, could you create a plunker? – Roman C Jun 19 '17 at 12:56
  • It's not my problem, but OP's problem, and your answer is wrong that's all. – Roman C Jun 19 '17 at 13:00
  • 1
    @RomanC Quoting from the OP, *I have a unordered
      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.
    – Okx Jun 19 '17 at 13:02
  • What? Angular is written on typescript. I said that's all. I won't answer your replies anymore. – Roman C Jun 19 '17 at 13:09
  • You're so right. Sometimes when working with Typescript and Angular you get so stuck in that mindset that you forget normal vanilla Javascript. Simple solution is a good one. – Marcus Lind Jun 19 '17 at 14:45
  • this answer is not correct, the way you described is not angularish – Hesham Yassin Nov 17 '17 at 10:04