Ionic3 - ionic element/component 在 innerHTML 中不起作用
Ionic3 - ionic element/component not working in innerHTML
我正在组件中创建动态 HTML,但正常的离子样式不起作用。
在 html 中:
<div [innerHTML]="testHtml"> </div>
在组件中(ts)
public testHtml = "<button color='secondary' ion-button>Default</button>";
我也尝试相信 html 使用管道,但这只使内联样式有效:
在管道中:
this.sanitizer.bypassSecurityTrustHtml(html);
此问题与
相同
由于 ionic 是 angular 之上的框架,angular 无法解析 ionic 自定义元素,也无法对其应用正确的 CSS,因为解析发生在 innerHTML 之前被添加。
因此,就此而言,我建议不要在innerHTML
指令中创建元素。让 innerHTML
的用法留在文本格式中。
Angular 是为了将 html 元素放入 html 模板(.html 文件或模板:属性)。
无论你在做什么,你想要在 innerHTML 中创建 html 你可以像这样将它放在 .html 文件中,只需放置一个 [ngIf] directive to show or hide the element or perhaps use the [ngClass] 指令来添加一个特定的 class 到元素。
<div>
<button [ngIf]="someTrueCondition; else showTheOtherElement" color='secondary' ion-button>Default</button>
<ng-template #showTheotherElement>
<button color='primary' ion-button>Default</button>
</ng-template>
</div>
Angular 清理所有动态添加的 HTML.
解决方案很简单 - 使用管道
从 '@angular/core' 导入 { Pipe, PipeTransform };
从“@angular/platform-browser”导入 {DomSanitizer};
@Pipe({
name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
并使用内部HTML标签并添加你的管道
<div [innerHTML]="question | safeHtml"></div>
在这里工作。
我正在组件中创建动态 HTML,但正常的离子样式不起作用。
在 html 中:
<div [innerHTML]="testHtml"> </div>
在组件中(ts)
public testHtml = "<button color='secondary' ion-button>Default</button>";
我也尝试相信 html 使用管道,但这只使内联样式有效:
在管道中:
this.sanitizer.bypassSecurityTrustHtml(html);
此问题与
由于 ionic 是 angular 之上的框架,angular 无法解析 ionic 自定义元素,也无法对其应用正确的 CSS,因为解析发生在 innerHTML 之前被添加。
因此,就此而言,我建议不要在innerHTML
指令中创建元素。让 innerHTML
的用法留在文本格式中。
Angular 是为了将 html 元素放入 html 模板(.html 文件或模板:属性)。 无论你在做什么,你想要在 innerHTML 中创建 html 你可以像这样将它放在 .html 文件中,只需放置一个 [ngIf] directive to show or hide the element or perhaps use the [ngClass] 指令来添加一个特定的 class 到元素。
<div>
<button [ngIf]="someTrueCondition; else showTheOtherElement" color='secondary' ion-button>Default</button>
<ng-template #showTheotherElement>
<button color='primary' ion-button>Default</button>
</ng-template>
</div>
Angular 清理所有动态添加的 HTML.
解决方案很简单 - 使用管道
从 '@angular/core' 导入 { Pipe, PipeTransform }; 从“@angular/platform-browser”导入 {DomSanitizer};
@Pipe({
name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
并使用内部HTML标签并添加你的管道
<div [innerHTML]="question | safeHtml"></div>
在这里工作。