You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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>
    `
  })
};

关键说明

  1. 内容投影写法:在render函数的模板中,将app-button-atom嵌套在app-header内部,同时添加#mainButton模板引用,这样HeaderComponent的@ContentChild就能正确捕获到该按钮实例。
  2. 独立组件导入:由于ButtonComponent是独立组件,需要通过decorators中的moduleMetadata导入它,否则Storybook无法渲染该组件。
  3. 动态参数控制:通过argTypes定义buttonText等可配置参数,就能在Storybook的控制面板中实时调整按钮文本,无需修改代码。

内容的提问来源于stack exchange,提问作者Charles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:13:02