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

如何为Kebab Case选择器的Angular指令传递第二个输入?

用Kebab Case实现Angular指令多输入的正确方式

完全可以用kebab-case的选择器实现多输入传递,问题出在输入别名的设置和模板语法的匹配上,以下是具体解决方案:

1. 指令代码调整

确保第二个输入的别名或属性名能和模板中的kebab-case写法对应,两种方式可选:

方式一:给第二个输入设置kebab-case别名

@Directive({
    selector: '[example-directive]', // 保持kebab-case选择器
})
export class ExampleDirective implements OnChanges {
    // 主输入:别名与选择器一致,对应模板中第一个值
    @Input('example-directive') input1: string;

    // 第二个输入:设置kebab-case别名
    @Input('example-directive-input2') input2: string;
}

方式二:利用Angular自动驼峰转kebab的特性

不需要额外设置别名,直接用驼峰命名输入属性,模板中用kebab-case引用即可:

@Directive({
    selector: '[example-directive]',
})
export class ExampleDirective implements OnChanges {
    @Input('example-directive') input1: string;
    // 驼峰命名的输入属性
    @Input() exampleDirectiveInput2: string;
}

2. 模板的正确写法

使用结构型指令语法*example-directive时,第一个值绑定到主输入(example-directive对应的input1),后续输入用键值对形式,键名要和指令中的设置匹配:

对应方式一的模板写法

<div *example-directive="'value1'; example-directive-input2: 'value2'"></div>

对应方式二的模板写法

Angular会自动把模板中的kebab-case转成驼峰属性名,所以两种写法都有效:

<div *example-directive="'value1'; example-directive-input2: 'value2'"></div>
<!-- 也可以直接用驼峰键名 -->
<div *example-directive="'value1'; exampleDirectiveInput2: 'value2'"></div>

你之前尝试失败的可能原因

你之前设置@Input('input2') exampleDirectiveInput2: string;、模板写input2: 'value2'理论上可行,但需要确保:

  • 指令类中输入声明无拼写错误
  • 模板中的键名input2和别名完全一致(大小写敏感)

如果仍有问题,建议优先使用和选择器同前缀的kebab-case别名(比如example-directive-input2),这更符合Angular命名规范,也能避免歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:05:26