How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

后端 未结 15 1924
忘掉有多难
忘掉有多难 2020-11-21 05:14

I want to dynamically create a template. This should be used to build a ComponentType at runtime and place (even replace) it somewhere inside of the ho

15条回答
  •  遥遥无期
    2020-11-21 05:43

    If all you need as a way to parse a dynamic string and load components by their selectors, you may also find the ngx-dynamic-hooks library useful. I initially created this as part of a personal project but didn't see anything like it around, so I polished it up a bit and made it public.

    Some tidbids:

    • You can load any components into a dynamic string by their selector (or any other pattern of your choice!)
    • Inputs and outputs can be se just like in a normal template
    • Components can be nested without restrictions
    • You can pass live data from the parent component into the dynamically loaded components (and even use it to bind inputs/outputs)
    • You can control which components can load in each outlet and even which inputs/outputs you can give them
    • The library uses Angular's built-in DOMSanitizer to be safe to use even with potentially unsafe input.

    Notably, it does not rely on a runtime-compiler like some of the other responses here. Because of that, you can't use template syntax. On the flipside, this means it works in both JiT and AoT-modes as well as both Ivy and the old template engine, as well as being much more secure to use in general.

    See it in action in this Stackblitz.

提交回复
热议问题