Ziv Barber
Ziv Barber

Reputation: 741

Angular 10: how to create dynamic Component / html?

2 questions:

  1. <div>{{ someData }}</div> - how to make {{ someData }} to be converted to html?
  2. <div>{{ MyComponentClass }}</div> - how to make it to create an instance of the component MyComponentClass and put it inside the div?

For question 1 I guess I need a way to get access to the DOM element and then to inject it myself. For question 2 I have no clue but it'll be so useful.

Upvotes: 0

Views: 3338

Answers (1)

Havald
Havald

Reputation: 739

  1. Question:

You can bind a string/html variable to the [innerHTML] attribute binding.

<div [innerHTML]="theHtmlString"></div>

If the html doesnt work you need to inject the DomSanitizer to tell angular that the html is safe.

 constructor(private sanitizer:DomSanitizer) {
    this.htmlString = this.sanitizer.bypassSecurityTrustHtml(style);
  }
  1. Question:

You can create components dynamically by using a @ViewChild and get the ViewContainerRef from your div and use the componentFactoryResolver:

Template:

<div #yourdiv></div>

Component:

@ViewChild("yourdiv" , {read: ViewContainerRef}) private vcr: ViewContainerRef;
   
constructor(private componentFactoryResolver: ComponentFactoryResolver) {

    let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    let componentFactory =  this.vcr.createComponent(resolver);
  
  }

Upvotes: 1

Related Questions