簡體   English   中英

如何使用Angular數據綁定來渲染組件?

[英]How can I use Angular data binding to render component?

在我的dashboard.component.html我具有以下代碼:

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

dashboard.component.ts內部,我有以下代碼:

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

我希望它在此處呈現消息組件。 但是它只是空白。 如果我將html中的代碼切換為<div><app-messages></app-messages></div>那么它可以按預期工作,但我不想直接包含它。

如果您好奇為什么我需ngFor ,那是因為我包括一個ngFor並且只想按順序呈現dashboard.component.ts中某個存儲桶數組中的組件。

謝謝。

我認為最好的方法還沒有在這里使用ngFor。 您還可以使用動態組件加載,但是在這種情況下,這可能會顯得過大。

@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;
}

工作示例: https : //stackblitz.com/edit/angular-audxwo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM