如何在多个mat-step中实现相同内容的内容投影?
解决Mat-Stepper共享步骤内容的问题
你原来用ng-content的方式行不通,因为ng-content的内容投影是一次性的——同一个内容只能被投影到一个位置,第二个<mat-step>里的<ng-content>会是空的。
要实现两个步骤复用相同内容,应该用ng-template结合ngTemplateOutlet来实现,具体代码如下:
<mat-stepper> <mat-step label="do this"> <!-- 复用共享模板 --> <ng-container *ngTemplateOutlet="sharedStuff"></ng-container> <p>unique step 1 stuff...</p> </mat-step> <mat-step label="do that"> <!-- 再次复用共享模板 --> <ng-container *ngTemplateOutlet="sharedStuff"></ng-container> <p>unique step 2 stuff...</p> </mat-step> </mat-stepper> <!-- 定义共享内容模板 --> <ng-template #sharedStuff> ...shared content... </ng-template>
额外优化:给共享模板传递上下文
如果需要根据不同步骤给共享内容传递差异化数据,可以用ngTemplateOutletContext:
<mat-stepper> <mat-step label="do this"> <ng-container *ngTemplateOutlet="sharedStuff; context: { stepName: '步骤1' }"></ng-container> <p>unique step 1 stuff...</p> </mat-step> <mat-step label="do that"> <ng-container *ngTemplateOutlet="sharedStuff; context: { stepName: '步骤2' }"></ng-container> <p>unique step 2 stuff...</p> </mat-step> </mat-stepper> <ng-template #sharedStuff let-stepName="stepName"> 这是{{ stepName }}的共享内容 </ng-template>
这种方式可以让共享模板根据当前步骤动态调整内容,灵活性更高。
内容的提问来源于stack exchange,提问作者patrick
相关产品推荐
相关产品推荐

