My end goal is to have user created HTML (from a database) with ability to navigate within an Angular SPA. The simple way to display HTML from a backend is to use the DomSanitizer then bind to innerHTML
of some element. The problem arises when an anchor tag <a href="/path/to/diffrent/page/in/app">
in the user created content reboots the app. I have thought of 3 solutions and they all have problems.
Note: I'd like to fully utilize AOT and build-optimizer.
(dynamic component with JIT compiler)
The user created content will have angular syntax like<a [routerLink]="/path/to/diffrent/page/in/app">
. Then use the example here of loading the runtime compiler withJitCompilerFactory
and custom decorators to preserve the component and module metadata to JIT compile components with the user created content as templates. However with build-optimizer this requires restoring the ctorParameters. With this you don't get all the size benefits of AOT because you still need to load the JIT compiler and as stated here - " And it seems to be risky as compiler is subject to internal changes. It works for @angular/compiler@4.4.5 but may not work for other releases."(DOM manipulation)
Leave proper HTML in user created content<a href="/path/to/diffrent/page/in/app">
. Then after binding toinnerHTML
get an ElementRef, then find every anchor tag and override the click event. This kind of DOM manipluation seems very discouraged in angular.(custom window event)
The user created content will look like<a onclick="window.someGlobalFunc("/path/to/diffrent/page/in/app")">
. Then listen to a window event in angular somehow. I like this idea even less as it is completely outside of angular.
edit add:
- (listen to the container "click" event and filter if it came from a anchor)
See @cyrix 's answer
What is the correct way to achieve this functionality?
edit update:
I accepted an answer as the "best" option, but if anyone finds or they release an "Angular" way to do this please add an answer.