Angular2 - Dynamic components in content received by API

后端 未结 3 630
礼貌的吻别
礼貌的吻别 2021-01-22 17:04

I have a component . The content for this component is received by API and it contains another components .

The question is, how to render the child component. When I pu

3条回答
  •  清酒与你
    2021-01-22 17:42

    Here is good solution with safeHtml directive: https://github.com/ngx-translate/core/issues/354

    You create a directive:

    import { Directive, ElementRef, Input, OnChanges, Sanitizer, SecurityContext,
      SimpleChanges } from '@angular/core';
    
    // Sets the element's innerHTML to a sanitized version of [safeHtml]
    @Directive({ selector: '[safeHtml]' })
    export class HtmlDirective implements OnChanges {
      @Input() safeHtml: string;
    
      constructor(private elementRef: ElementRef, private sanitizer: Sanitizer) {}
    
      ngOnChanges(changes: SimpleChanges): any {
        if ('safeHtml' in changes) {
          this.elementRef.nativeElement.innerHTML =
            this.sanitizer.sanitize(SecurityContext.HTML, this.safeHtml);
        }
      }
    }
    

    and use it as following:

提交回复
热议问题