首页 文章

动态渲染的垫扩展面板无法按预期工作

提问于
浏览
0

我需要动态渲染手风琴中的扩展面板列表 .

标记很简单:

<mat-accordion *ngIf="currentVenue">
  <mat-expansion-panel *ngFor="let gig of currentVenue.gigs" expanded="false">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{gig.name}}
      </mat-panel-title>
      <mat-panel-description>
        Type your name and age
      </mat-panel-description>
    </mat-expansion-panel-header>

  </mat-expansion-panel>
</mat-accordion>

不幸的是,这会导致无法控制 . Headers 没有打开面板,整个手风琴功能也搞砸了 . 我需要在控件外部单击,然后随机打开一个子扩展面板(或不打开) .

如果我反过来使用“静态”方法(我从示例代码中复制了这个),一切都按预期工作:

<mat-accordion>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      <mat-panel-title>
        Personal data
      </mat-panel-title>
      <mat-panel-description>
        Type your name and age
      </mat-panel-description>
    </mat-expansion-panel-header>

    <mat-form-field>
      <input matInput placeholder="First name">
    </mat-form-field>

    <mat-form-field>
      <input matInput placeholder="Age">
    </mat-form-field>
  </mat-expansion-panel>
  [...]
</mat-accordion>

我的猜测是,它与 *ngIf 以及控件的创建方式有关 .

我正在使用Angular Material 6.4.7和Angular 6.1.10

1 回答

  • 0

    你在这里做一些有趣的事情你是对的 . 它是一个结构指令,因此在较低级别,Angular使其与其他组件不同 . 此渲染可能会干扰其他结构指令,因此Angular只允许模板一次绑定到一个结构指令 .

    但好消息!名称中的星号只是结构指令真正起作用的语法糖 . 如果我们对名称进行去糖并将其明确地绑定到模板上,包含手风琴本身,Angular将能够使用此模板上下文而不是使用组件的模板来呈现嵌套指令:

    <ng-template [ngIf]="currentVenue">
        <mat-accordion>
          <mat-expansion-panel *ngFor="let gig of currentVenue.gigs" expanded="false">
            <mat-expansion-panel-header>
              <mat-panel-title>
                {{gig.name}}
              </mat-panel-title>
              <mat-panel-description>
                Type your name and age
              </mat-panel-description>
            </mat-expansion-panel-header>
    
          </mat-expansion-panel>
        </mat-accordion>
      </ng-template>
    

    注意 ngIf 现在如何绑定为常规指令 . 这只能用于 ng-template 标签 . 如果没有星号,Angular将不会尝试将不同的模板绑定到它,并且嵌套指令将起作用 .

    我们也可以给重复的项目自己 ng-templatengForOf 指令,但 [ngIf] 的语法更清晰 .

相关问题