我有一个类似的问题,我有一个卡片组件,它有一个子卡片头组件以及一个卡片主体的选择器。
card-header 组件有一个切换按钮,用于调度打开/关闭卡片的操作。
然后我需要能够通过卡片组件将额外的按钮从父组件传递到卡片头组件
我通过在每个级别添加选择器来解决它。
首先,我创建了一个通用的卡片头组件,允许我拥有一段代码,通过向 NgRx 存储发送操作来处理切换卡片内容,该存储包含一组隐藏的卡片(使用提供的名称输入属性)。
当toggled 状态发生变化时,card-header 组件订阅 store 并向父组件发出事件
@Component({
selector: 'po-card-header',
template: `
<div class="card-header">
<span class="text-uppercase">{{ header }}</span>
<div class="header-controls">
<ng-content select=[card-header-option]></ng-content>
<ng-content select=[header-option]></ng-content>
<span class="header-action" (click)="onTogglePanel()">
<i class="fa" [ngClass]="{ 'fa-caret-up': !collapsed, 'fa-caret-down': collapsed}"></i>
</span>
</div>
</div>
`
})
export class CardHeaderComponent implements OnInit, OnDestroy {
...
@Input() name: string;
@Output() togglePanel = new EventEmitter<boolean>();
collapsed$: Observable<boolean>;
collapsedSub: Subscription;
constructor(private store: Store<State>) {
this.collapsed$ = this.store.select(state => getPanelCollapsed(state, this.name);
}
ngOnInit(): void {
this.collapsedSub = this.collapsed$.subscribe(collapsed => {
this.collapsed = collapsed;
this.togglePanel.emit(collapsed);
});
}
.... unsubscribe on destroy.
}
注意标题有 2 个ng-content 部分。
header-option 选择器适用于我在明确使用此组件时要添加的任何其他图标,例如
<div class="card">
<po-card-header>
...
<span header-option class="fa fa-whatever" (click)="doSomething()"></span>
</po-card-header>
...
</div>
我的新图标将位于标题中的默认切换图标旁边。
第二个card-header-option 选择器用于根组件,它使用卡片组件,而不是卡片标题组件,但仍希望将额外的图标传递到标题中。
@Component({
selector: 'po-card',
template: `
<div class="card">
<po-card-header>
...
<ng-content select="[card-header-option] header-option></ng-content>
</po-card-header>
<div class="card-block">
<ng-content select="[card-body]"></ng-content>
</div>
</div>
`
})
...
[card-header-option] 选择器将选择具有该属性的任何元素,然后使用 header-option 属性将它们传递到卡片标题组件
我的卡片组件最终的用法是这样的。
<div>
Some component that uses the card
<po-card
header="Some text to go in the card header"
name="a-unique-name-for-the-card">
<span card-header-option class='fa fa-blah header-action'></span>
<div card-body>
Some content that gets put inside the [card-body] selector on the card component.
</div>
</po-card>
</div>
最终的结果是我可以使用我的自定义卡片组件,并获得卡片标题组件提供的切换功能的好处,还可以提供我自己的自定义操作,这些操作也会在标题中呈现
希望你觉得这对你有帮助:-)