網站搜尋

typescript - Angular - 如何將 Angular 變數綁定到 HTML 並顯示


我有一個組件,它有一個 ts 文件,裡面包含作為變數的 HTML 內容。

para1= <a href="www.google.com">網站名稱</a> 更多內容

我需要將這段文字像 HTML 本身一樣綁定在 HTML 中。

網站名稱

我該如何達成這個目標?

答案#1

如果你的變數值包含 HTML 模板,只需使用 innerHTML。

像這樣 -

para1= "<a href="www.google.com">sitename</a> more content"

在 HTML 文件中 -

<span [innerHTML]='para1'></span>

答案#2

你可以使用 ngx-dynamic-template 來達成這個目的。

在你的範例中,當 para1= '<a href="www.google.com">sitename</a> . . .' 時,你可能會有像這樣的東西:

<ng-template 
    dynamic-template
    [template]="para1"
>
</ng-template>

別忘了你的匯入項:

import { NgxDynamicTemplateModule } from 'ngx-dynamic-template';

@NgModule({
    imports: [NgxDynamicTemplateModule.forRoot()]
})