Long time user, first time question asker! I've been trying to figure this out for the better part of two days to no avail, so here we go.
Dynamic compiled templates from external sources in Angular2?
I am using http to get page content in the form of HTML from the WordPress API. So I have a template like this:
<div [innerHTML]="contentHTML"> </div>
and "contentHTML" is a string variable in the component and assigned a value asynchronously via the API call to something like this:
<a routerLink="/help/faq.html"> </a>
and I want that routerLink to work. Of course routerLink could be anything that's valid in a template.
If the above is not possible
If the above isn't going to work, what about a way to interpret the incoming HTML and add routerLinks on the fly to replace standard hrefs?
After much digging, I found the answer to Angular 2.1.0 create child component on the fly, dynamically very useful in getting things working!
THE SECRET SAUCE!!!
Checkout the complete Plunker example by yurzui for details, but in a nutshell, make sure that the DynamicHtmlModule class which creates the runtime compiled component has a reference to the RouterModule module. Otherwise routerLink directives used in the dynamic template will not work. I've bolded the key piece of code below.
The same is going to be true for any other directive or component your template might use. You have to make sure your DynamicHtmlModule properly references them to get them to work.
I came across the same issue, I followed this answer, but added a simple modification in the code where you import DynamicComponentModule, but added imports: [RouterModule]
So the steps would be as following install ng-dynamic:
Then use the following import and code:
Then instead of:
Use:
hope this helps!
One possible solution without using Dynamic runtime compilation when using hash location strategy is to use the following HTML
where
/pages/Home
is an angular route. This will be set into a div as followsThis will trigger a reload on the destination, hence handing over stuff to angular router.
UPDATE 1
I used a neater workaround for this using custom events. I added a custom js as follows
I listen to this event using RxJs, in constructor of a custom service injected into
app.module
Finally, my HTML