[英]Angular 5 - Bind a component selector with InnerHtml
我有一個名為“app-component1”的 component1 選擇器。
@Component({
selector: 'app-component1',
templateUrl: './test-widget.component.html',
styleUrls: ['./test-widget.component.scss'] })
所以要調用這個組件的 html 我通常使用:
<app-component1></app-component1>
它工作得很好。
現在從另一個 component2 我有以下變量:
variableToBind = "<app-component1></app-component1>";
在組件 2 的 html 中,我使用了以下內容:
<div [innerHtml]="varibableToBind"></div>
html 代碼綁定不起作用。 是否有可能幫助我理解原因並可能幫助我找到另一種選擇?
感謝大家的建議,我實際上只是找到了答案:
這是行不通的,因為 innerHtml 是在 Angular 編譯模板之后呈現的。 這意味着它此時不了解您的選擇器。
如果你們想動態加載一個組件(或任何內容),你應該使用 *ngIf。 它對我來說非常好。
您的示例代碼不是有效的方法
1) 出於安全原因,html 代碼不能直接綁定到元素屬性。 參考: https ://angular.io/guide/security#xss
2) 在您的情況下,無需對 HTML 進行屬性綁定。 如果你想在AppComponent2
內部執行不同的邏輯,最好的做法是對可以自定義組件行為的參數進行屬性綁定:
<div>
<app-component1 [prop1]="myVar1" [prop2]="myVar2"></app-component1>
</div>
然后您可以從組件屬性而不是組件本身對其進行自定義。 這會更有意義。
如果您確實需要將HTML
傳遞給組件(例如,如果您有帶有<br>
標簽的文本或類似的東西),您可以像這樣創建自定義Input
:
export class YourComponent {
@Input() public htmlContent = '';
}
<div [innerHtml]="htmlDescription"></div>
並像這樣使用它:
<your-component [htmlDescription]="textWithHtmlTags"></your-component>
* - 例如,如果需要呈現帶有基本HTML
格式標記(如<b>
、 <i>
甚至<br>
)的文本字符串。
在 Angular 中,一般不建議使用 [innerHTML] 綁定來綁定組件選擇器,因為這會導致安全漏洞。 相反,您應該使用 Angular 的模板語法和組件結構將組件包含在您的模板中。
如果您需要根據某些條件動態選擇要包含的組件,則可以使用 ngIf 指令和元素僅在滿足特定條件時才包含組件。
<ng-template [ngIf]="showMyComponent">
<my-component></my-component>
</ng-template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.