innerHtml +花括号的角度5问题

时间:2018-05-03 07:38:35

标签: javascript angular innerhtml

我正在尝试在控制器中使用带花括号的HTML模板。

我发现的问题是,当我将innerHTML与safePipe一起使用时,我会看到花括号,而不是结果。

home.html (模板)

<ul>
  <li *ngFor="let item of events">
    {{item.name}}
  </li>
</ul>

sanitizing.ts

@Pipe({name: 'safe'})
export class SafePipe implements PipeTransform {

constructor(protected sanitizer: DomSanitizer) {}

public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
  switch (type) {
    case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
    case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
    case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
    case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
    case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
    default: throw new Error(`Invalid safe type specified: ${type}`);
   }
 }
}

home.component.html

<div [innerHtml]="myTemplate | safe: 'html'"></div>

结果

{{item.name}}

期望的结果

dummy

1 个答案:

答案 0 :(得分:1)

innerHTML无法编译角度模板。

如果您想以动态方式插入组件,请参阅angular docs dynamic component loader

 loadComponent() {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(Type.component);


    let componentRef = viewContainerRef.createComponent(componentFactory);
  }