Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

angular - Angular2 Dynamic HTML with functional RouterLink

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

npm install --save ng-dynamic

Then use the following import and code:

import { DynamicComponentModule } from 'ng-dynamic';

@NgModule({
   imports: [
       ...
       DynamicComponentModule.forRoot({imports: [RouterModule]}),
       ...
   ],
   ...
})
export class AppModule {} 

Then instead of:

<div [innerHTML]="contentHTML"> </div>

Use:

<div *dynamicComponent="contentHTML"></div>

hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...