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

1

1 Answer 1

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.

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

1 Comment

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?

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.