【问题标题】:Angular: How to dynamically add components to parent Dashboard component?Angular:如何将组件动态添加到父仪表板组件?
【发布时间】:2018-05-30 19:10:16
【问题描述】:

我有两个组件。一个是卡片仪表板(使用 ng generate @angular/material:material-dashboard --name=my-dashboard 创建),其中卡片的创建方式如下:

<div class="grid-container">
 <h1 class="mat-h1">Dashboard</h1>
 <mat-grid-list cols="2" rowHeight="350px">
  <mat-grid-tile *ngFor="let card of cards" [colspan]="card.cols" [rowspan]="card.rows">
   <mat-card class="dashboard-card">
    <mat-card-header>
     <mat-card-title> {{card.title}}
      <button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
       <mat-icon>more_vert</mat-icon>
      </button>
      <mat-menu #menu="matMenu" xPosition="before">
       <button mat-menu-item>Expand</button>
       <button mat-menu-item>Remove</button>
      </mat-menu>
     </mat-card-title>
    </mat-card-header>
    <mat-card-content class="dashboard-card-content">
      <div>{{ card.content }}</div>
    </mat-card-content>
   </mat-card>
  </mat-grid-tile>
 </mat-grid-list>
</div>

而且是这样填充的:

export class DashComponent {
 cards = [
  { title: 'Character', cols: 2, rows: 1, content: '<app-character-sheet></app-character-sheet>' },
  { title: 'Card 2', cols: 1, rows: 1 },
  { title: 'Card 3', cols: 1, rows: 2 },
  { title: 'Card 4', cols: 1, rows: 1 }
 ];
}

我想用不同的组件填充卡片。但是当我像你在上面看到的那样尝试它时(使用 content 变量),HTML 没有解析选择器。卡片只是文字内容:.

如何用组件动态填充我的卡片?

干杯

【问题讨论】:

  • {{x}} 是字符串插值,因此它最终会作为字符串传递给 html div。您可以通过将属性绑定到 div 来做到这一点。

标签: html angular typescript


【解决方案1】:

如果确实需要动态插入组件,请阅读this 文章。

对于内容选项集有限的情况,另一种解决方案是使用 ngIfngSwitchCase 等结构指令:

<mat-card-content class="dashboard-card-content">
  <div *ngIf="card.content"><app-character-sheet></app-character-sheet></div>
</mat-card-content>

您可以不安全地插入 HTML 而不进行后期处理(但不推荐):

<div [innerHTML]="card.content"></div>

【讨论】:

  • 使用innerHTML 是完全错误的。 Angular 不会处理通过 innerHTML 动态添加到模板的 HTML。该解决方案将使OP无处可去。如果组件集不太大或按照文章所说的那样做是最好的选择,则使用条件。
  • Narm,我演示了innerHTML 作为最简单的选项。
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多