如何在Storybook中为组件传递@ContentChild属性?
在Storybook中为带@ContentChild的组件传递内容子元素
你当前直接在args中实例化ButtonComponent的写法是错误的,因为@ContentChild是用来捕获通过内容投影传入的子组件,而非通过@Input传递的属性。以下是正确的实现方式:
核心原理
@ContentChild('mainButton')会查找组件内容区域中带有#mainButton模板引用变量的子组件,因此需要将ButtonComponent作为HeaderComponent的内容子元素传入,而非作为props参数传递。
修改后的Story代码
import { Meta, StoryObj } from '@storybook/angular'; import { HeaderComponent } from './header.component'; import { ButtonComponent } from './button.component'; const meta: Meta<HeaderComponent> = { title: 'Header', component: HeaderComponent, tags: ['autodocs'], // 定义可在Storybook面板中调整的参数 argTypes: { hasBackButton: { control: 'boolean', defaultValue: true }, buttonText: { control: 'text', defaultValue: '主按钮' } }, // 导入独立组件ButtonComponent decorators: [ (story) => ({ ...story, moduleMetadata: { imports: [ButtonComponent] } }) ] }; export default meta; type Story = StoryObj<HeaderComponent>; export const Default: Story = { args: { hasBackButton: true, buttonText: '主按钮' }, render: (args) => ({ props: args, template: ` <app-header [hasBackButton]="hasBackButton"> <!-- 通过内容投影传入带模板引用的按钮组件 --> <app-button-atom #mainButton [text]="buttonText"></app-button-atom> </app-header> ` }) };
关键说明
- 内容投影写法:在
render函数的模板中,将app-button-atom嵌套在app-header内部,同时添加#mainButton模板引用,这样HeaderComponent的@ContentChild就能正确捕获到该按钮实例。 - 独立组件导入:由于
ButtonComponent是独立组件,需要通过decorators中的moduleMetadata导入它,否则Storybook无法渲染该组件。 - 动态参数控制:通过
argTypes定义buttonText等可配置参数,就能在Storybook的控制面板中实时调整按钮文本,无需修改代码。
内容的提问来源于stack exchange,提问作者Charles
相关产品推荐
相关产品推荐

