Angular: How to dynamically load a component defined by a string?

和自甴很熟 提交于 2020-06-28 09:07:08

问题


How do I compile a component defined by a string and render it in my template?

I tried using DomSanitizer:

this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);

But that doesn't properly bind the click event handler onButtonClick().

Desired Functionality

@Component({
    selector: 'app-sample-component',
    templateUrl: './sample-component.component.html',
    styleUrls: ['./sample-component.component.scss']
})
export class SampleComponent {

  buildMessage() {
    // How do I parse this string and render so that it responds to events?
    const myOutput = '<button (click)="onButtonClick()';
  }

  onButtonClick() {
    console.log('Handler for Dynamic Button');
  }

}


回答1:


The Angular security model is designed such that HTML added to [innerHTML]="myOutput" is not processed (i.e. scripts are not executed and events are not triggered).

Angular options to compile HTML include:

Add HTML to a Component Template

In your example, the HTML would go in sample-component.component.html. To dynamically include or exclude HTML in a template, use structural directives such as *ngIf and *ngFor.

Create a Dynamic Component to load at Runtime

See Dynamic Component Loader

Stackblitz Demo



来源:https://stackoverflow.com/questions/58087736/angular-how-to-dynamically-load-a-component-defined-by-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!