Angular组件ng-content在Storybook Stories中失效问题排查
问题排查方向
1. 组件定义未正确绑定输入属性与ng-content
先检查anchor.component.ts里的组件代码,确保href输入属性和ng-content的使用都没问题:
import { Component, Input } from '@angular/core'; @Component({ selector: 'lib-anchor', standalone: true, template: `<a [href]="href"><ng-content></ng-content></a>`, }) export class LibAnchorComponent { @Input() href!: string; // 必须加@Input()装饰器,否则外部传值无效 }
要是没给href加@Input(),Storybook传的参数根本绑定不到组件上;如果ng-content放在<a>标签外面,传入的“hello world”也不会显示在链接里。
2. Storybook故事未正确传递属性和插槽内容
CSF 3.0 正确写法
要在args里定义href,同时在render函数的模板中正确传入插槽内容:
import { Meta, StoryObj } from '@storybook/angular'; import { LibAnchorComponent } from './anchor.component'; const meta: Meta<LibAnchorComponent> = { component: LibAnchorComponent, title: 'LibAnchorComponent', }; export default meta; type Story = StoryObj<LibAnchorComponent>; export const Primary: Story = { args: { href: 'https://google.com', }, render: (args) => ({ props: args, template: `<lib-anchor [href]="href">hello world</lib-anchor>`, }), };
很多人只在args里传href,但没在模板里把组件和插槽内容写对,自然不会生效。
CSF 2.0 正确写法
如果用CSF2,要保证故事的template部分正确:
import { Meta, StoriesOf } from '@storybook/angular'; import { LibAnchorComponent } from './anchor.component'; export default { title: 'LibAnchorComponent', component: LibAnchorComponent, } as Meta; const stories = StoriesOf('LibAnchorComponent', module); stories.add('Primary', () => ({ component: LibAnchorComponent, props: { href: 'https://google.com', }, template: `<lib-anchor [href]="href">hello world</lib-anchor>`, }));
3. Storybook Angular配置不兼容
检查.storybook/main.ts是否正确支持Angular独立组件,确保@storybook/angular版本在6.4以上(独立组件需要这个版本及以上支持),同时确认故事文件里正确导入了LibAnchorComponent,没遗漏独立组件的相关配置。
4. 组件模板语法错误
比如把[href]="href"写成href="{{href}}"(虽然也能生效,但如果是复杂场景可能出问题),或者引号使用错误;要是ng-content被注释、标签写错,也会导致插槽内容不显示。
内容的提问来源于stack exchange,提问作者Chrillewoodz
相关产品推荐
相关产品推荐

