我需要在一个手风琴中动态地呈现一个扩展面板列表。
标记非常简单:
<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>不幸的是,这导致了一个不可用的控件。页眉没有打开面板,整个折叠功能也被搞乱了。我需要在控件外部单击,然后随机打开一个子扩展面板(或不打开)。
如果我反过来使用“静态”方法(我从示例的代码中复制了这一点),一切都会按预期工作:
<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材质6.4.7和Angular 6.1.10
发布于 2018-10-16 04:53:57
你说得对,*ngIf在这里做了一些有趣的事情。它是一个结构化的指令,所以在较低的层次上,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-template和ngForOf指令,但是[ngIf]的语法要清晰得多。
https://stackoverflow.com/questions/52823625
复制相似问题