【问题标题】:Angular: Bind to an @Input aliasAngular:绑定到@Input 别名
【发布时间】:2021-01-27 05:42:13
【问题描述】:

我正在尝试在 example 之后的指令中设置输入别名

  @Input('appAvatarColor') name: string;

程序正在运行,但我收到了来自 TS Lint 的警告

指令输入属性不应重命名

指令选择器是这个

@Directive({
  selector: '[appAvatarColor]'
})

我做错了吗?
为什么默认情况下这被认为是不好的做法?

【问题讨论】:

  • 我怀疑你的 "no-input-rename": true 文件中有 "no-input-rename": true 规则
  • @yurzui 是的。这是正确的。我正在使用由 angular cli 生成的标准 tslint.json。我的问题是为什么默认情况下这被认为是一种不好的做法?

标签: angular


【解决方案1】:

您可以关闭tslint.json中的规则

"no-input-rename": false

或禁用仅检查特定行,例如:

// tslint:disable-next-line:no-input-rename
@Input('appAvatarColor') name: string;

我的问题是为什么默认情况下这被认为是一种不好的做法?

  • 同一财产的两个名称(一个私有,一个公共)本质上是混淆的。

  • 当指令名称也是输入属性,并且指令名称不描述属性时,您应该使用别名。

来自https://angular.io/docs/ts/latest/guide/style-guide.html#!#05-13

【讨论】:

  • 对于"-input-rename,我同意重命名令人困惑,毕竟字段的类型在外部/内部都保持不变。但是对于@Output,默认情况下还有一个no-output-rename: true。而且我发现这个逻辑更难理解,因为与输入不同,它不是对称的。例如在外部它看起来像一个事件:(rowDeleted)="onRowDelete($event)",但在内部它不是一个事件,而是一个EventEmitter。将其命名为 rowDeleted 会使它看起来像 boolean。将其定义为@Output('rowDeleted') private rowDeletedEventEmitter; 更有意义,对吧?
  • 尽管如此,这是一个很好的答案:)。但也很好奇您对no-output-rename 的看法。
  • 对于 eslint v8.2.0 写 "no-input-rename": 0 否则你会得到 Error: .eslintrc.json#overrides[0]:
【解决方案2】:

您可以通过以下方式实现它:

@Input() appAvatarColor: string;

【讨论】:

  • 我相信你没有在这里添加别名,你只是将你的变量声明为'appAvatarColor'而不是'name'
【解决方案3】:

您应该将@Input('appAvatarColor') name: string; 重命名为其他名称,以使其与指令名称不同。你可以做@Input('avatarColor') name: string;,然后通过@Input() avatarColor: string;简化它

【讨论】:

    【解决方案4】:

    正确的做法应该如下:

    @Input() appAvatarColor: string;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2018-09-29
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多