[英]Angular2 [innerHtml] angular2 tag doesn't work
我想用來自另一個組件的 angular2 標簽在我的 a 組件中注入 html。
@Component({
selector: 'app-root',
template: '<app-a [my-html]="my-html"> </app-a>',
styleUrls: ['./app.component.css']
})
export class AppComponent {
my-html= '<span> {{variableFromAComponent}}</span>';
}
@Component({
selector: 'app-a',
template: '<div [innerHtml]="my-html"> </div>',
})
export class AComponent {
@Input('my-html') my-html:any;
public variableFromAComponent='its work!';
}
我想看到結果:它的工作! (來自 variableFromAComponent)但我看到 {{variableFromAComponent}} (angular2 標簽不起作用)。
我在angular2-dynamic-component 中找到了解決方案
<template dynamic-component
[componentContext]="self"
[componentModules]="dynamicExtraModules"
[componentTemplate]='"here html tags with angular2 tags"'>
</template>
Angular 根本不處理由[innerHTML]="..."
添加的 HTML。 它只是按原樣添加,僅此而已。 您甚至可能需要使用 Sanitizer,因此出於安全原因,不會刪除任何內容(請參閱在 RC.1 中,某些樣式無法使用綁定語法添加)。
如果你想動態添加組件,你可以使用ViewContainerRef.createComponent()
例如像Angular 2 動態選項卡中解釋的那樣,用戶單擊選擇的組件
有幾種方法可以做到這一點。
如果組件之間存在父/子關系,則可以使用Input()
和Output()
在它們之間傳遞值
這個子組件通過Input()
獲取值
子組件.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'child',
template: '<div>{{myHtml}}</div>', // these curly braces add the text as innerHTML
providers: [ FoodsService]
})
export class ChildComponent implements OnInit {
@Input() myHtml: string;
}
這是從父級通過模板傳遞的:
父組件.html
<child [myHtml]="'You're String Here (or a variable set to "its work")'"></child>
您可以使用Output()
從孩子到父母。
另一種方法是創建一個注入到兩個組件中的服務。 一個組件可以向服務發送一個值,另一個可以獲取該值。 在 Angular2 中,這通常是通過對數據對象使用observable來實現的。
您可以為此使用Renderer2 類。
import { ElementRef, Renderer2 } from '@angular/core';
constructor (
private elementRef: ElementRef,
private renderer: Renderer
) {}
public ngAfertViewInit(): void {
this.renderer
.setElementProperty(
this.elementRef.nativeElement,
'innerHTML',
'<h1> Nice Title </h1>'
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.