5

I have a custom @NgComponent in my project and it works if I place it within the static HTML of the application. What I'm trying to figure out is how to add one to the DOM dynamically? If I construct an instance of my Component it does not appear to be of type Element and so it cannot be added directly to the children of an element in the DOM. Is there an alternate way to construct my component or wrap it for injection into the DOM?

e.g. I naively expected to be able to do something like:

dom.Element holderEl = dom.document.querySelector("#my-holder");
holderEl.children.add( new MyComponent() ); 

But I have also tried simply appending HTML containing my custom element to an element using innerHTML

holder.innerHtml="<my-component></my-component>"

and creating the element using document.createElement()

dom.Element el = dom.document.createElement("my-component");
dom.document.body.append(el);

But the component does not seem to be realized when added.

thanks, Pat

Mark E. Haase
  • 25,965
  • 11
  • 66
  • 72
Pat Niemeyer
  • 5,930
  • 1
  • 31
  • 35
  • 2
    have a look here: http://stackoverflow.com/questions/20423565/how-to-add-a-component-programatically-in-angular-dart – alearg Dec 08 '13 at 18:01

1 Answers1

1

You can add components dynamically, but you must manually invoke the Angular compiler so it notices that the innerHTML has a component embedded in it.

However, that is not the "Angular way".

Instead, write your template as

<div id="my-holder">
  <my-component ng-if="should_component_be_displayed"></my-component>
</div>

Here, my-component will be created and included in the DOM only if should_component_be_displayed is true.

The my-holder div can be removed which leads to a cleaner DOM structure.

James deBoer
  • 2,477
  • 15
  • 17
  • 6
    I want to understand what you're saying about the "Angular Way". Suppose I have a list, with a potential of say 300 items in that list. Each item can be of a different component, say 15 different types. Would it still make sense to create this list using ng-if statements for each one of the 15 different component types, or would you generate the list dynamically? – Greg Sherman Jun 09 '14 at 03:19