Angular 12中如何将组件数组作为输入传入自定义窗口类组件
Angular 实现可自定义操作按钮的窗口组件的理想方案
Angular 中对应 React 透传组件 props 的特性是内容投影(Content Projection),针对你这个窗口组件的需求,推荐使用具名内容投影实现固定槽位的自定义内容注入,该方案完全解耦了窗口通用布局逻辑和业务自定义内容,不需要为不同场景做任何 if 分支判断,可维护性和扩展性都符合 Angular 最佳实践,具体实现步骤如下:
步骤1:在窗口组件模板中定义具名插槽
在你的窗口组件(示例命名为app-window)的模板中,给右上角按钮区域预留具名投影槽:
<!-- window.component.html --> <div class="window-container"> <div class="window-header"> <h3 class="window-title">{{ title }}</h3> <!-- 右上角按钮的具名插槽 --> <div class="window-actions"> <ng-content select="[windowActions]"></ng-content> </div> </div> <div class="window-body"> <!-- 也可以同时预留正文区域的默认投影槽 --> <ng-content></ng-content> </div> </div>
步骤2:业务场景下传入自定义按钮
使用组件时,直接把你需要的任意按钮/自定义组件放到对应槽位即可,不需要修改窗口组件本身的逻辑:
<!-- 业务页面中使用窗口组件示例 --> <app-window title="用户管理"> <!-- 自定义右上角操作按钮,匹配select="[windowActions]"的插槽规则 --> <button windowActions (click)="openCreateModal()">新增用户</button> <button windowActions (click)="deleteSelected()">批量删除</button> <app-export-button windowActions [exportConfig]="exportParams"></app-export-button> <!-- 窗口正文业务内容 --> <div class="user-table"> <!-- 业务表格实现 --> </div> </app-window>
进阶场景:带上下文的动态投影
如果你的自定义按钮需要根据窗口组件内部的状态控制显示逻辑,或者需要调用窗口组件的内部方法,可以搭配 ng-template + TemplateRef 实现带上下文的投影:
- 窗口组件内部定义输入属性接收模板:
// window.component.ts import { Input, TemplateRef } from '@angular/core'; @Input() actionsTemplate: TemplateRef<any>;
- 窗口模板中渲染传入的模板,同时绑定上下文:
<div class="window-actions"> <ng-container *ngTemplateOutlet="actionsTemplate; context: { windowInstance: this }"></ng-container> </div>
- 业务侧传入模板即可获取窗口实例上下文:
<app-window title="订单管理" [actionsTemplate]="orderActions"> <!-- 正文业务内容 --> </app-window> <ng-template #orderActions let-window="windowInstance"> <button *ngIf="window.isEditable" (click)="saveOrder(window.id)">保存订单</button> <button *ngIf="!window.isEditable" (click)="enableEdit(window.id)">编辑</button> </ng-template>
内容的提问来源于stack exchange,提问作者Amol Borkar
相关产品推荐
相关产品推荐

