简体   繁体   中英

Render Angular 4 component with text coming in from an API

I want to render incoming text from an API as subsequent HTML and component template. Most of the solutions I found here use @ViewChild to inject the components but that doesn't work for me since I need to iterate the same behavior for all items in the *ngFor loop.

This is how the code would look like:

The template of the component rendering the incoming messages:

      <div *ngFor="let item of messages">
            <compile-component [template]="item.html"></compile-component>
      </div>

Incoming message structure (item.html):

<my-component></my-component><div>Some html</div>

Component to compile:

@Component({
  selector: 'my-component',
  template: '<div>It works</div>',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent{ }

Output would look like this:

<div>It works</div><div>Some html</div>

I am looking for the solution for compile-component here. Any help is much appreciated. Thanks in advance.

You should be able to do that via ComponentFactoryResolver . See angular docs about this here:

https://angular.io/guide/dynamic-component-loader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM