简体   繁体   中英

How can I use Angular data binding to render component?

On my dashboard.component.html I have the following code:

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

Inside of dashboard.component.ts I have the following code:

myComponent = "<app-messages></app-messages>"

I want it to render the messages component there. But it just appears blank. If I switch the code in the html to simply be <div><app-messages></app-messages></div> then it works as expected, but I don't want to directly include it like that.

In case you are curious why I need this, it is because I am including an ngFor and only want to render, in order, the components in a certain bucket array within dashboard.component.ts.

Thank you.

I think the best way is yet to use ngFor here. You can also use dynamic component loading, but this would be overkill in this case.

@Component({
    selector: 'items',
    template: `
      <item *ngFor="let i of service.items;" [name]="i"></item>
    `,
})
export class ItemsComponent {
    constructor(public service: ItemsService) { }
}

@Component({
    selector: 'item',
    template: `<div>{{name}}</div>`,
})
export class ItemComponent {
    @Input() name: string;
}

Working example: https://stackblitz.com/edit/angular-audxwo

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