Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.Dart How to dynamically add Component to DOM?

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

like image 382
Pat Niemeyer Avatar asked Nov 12 '22 18:11

Pat Niemeyer


1 Answers

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.

like image 100
James deBoer Avatar answered Dec 23 '22 15:12

James deBoer