简体   繁体   English

angular 指令选择器和 tslint 之间的冲突

[英]The conflict between angular directive selector and tslint

I am using angular 4 directive to define an angular attribute directive.我正在使用 angular 4 指令来定义一个 angular 属性指令。 But I want to use this directive as a class.但我想将此指令用作一个类。 My definition is (It works fine) :我的定义是(它工作正常):

@Directive({
  selector: '.input-field'
})

This is according to angular selector definition (the .class one)这是根据角度选择器定义( .class之一)

在此处输入图片说明

But I got a tslint error as below:但是我收到了一个 tslint 错误,如下所示:

tslint 错误

Is there any way to fix this error without disable the tslint rule?有没有办法在不禁用 tslint 规则的情况下修复此错误?

In this case your rule prevents you from using class selectors so you have to disable it.在这种情况下,您的规则会阻止您使用类选择器,因此您必须禁用它。 The question is to disable it globally or not?问题是是否全局禁用它?

You can disable a specific rule in a block of code like that:您可以在代码块中禁用特定规则,如下所示:

/* tslint:disable: no-use-before-declare */

some code breaking no-use-before-declare rule

/* tslint:enable: no-use-before-declare */

Or you can disable entire tslint for the next line或者您可以为下一行禁用整个 tslint

// tslint:disable-next-line
some code breaking all the rules
normal code

To have multiple prefixes validated in the same project, you can just use the following (in tslint.json file):要在同一个项目中验证多个前缀,您只需使用以下内容(在tslint.json文件中):

...
"component-selector": [true, "element", ["app", "my-awsome-prefix", "another-prefix"], "kebab-case"],
...

And same for the Directives:指令也一样:

...
"directive-selector": [true, "attribute", ["app", "myDirectivePrefix"], "camelCase"],
...

I faced the same error and opened an issue on GitHub .我遇到了同样的错误并在GitHub 上打开了一个问题。 This is the answer I got:这是我得到的答案:

While Angular does support class selectors for directives, this feature should be used only in special circumstances because it makes it hard to understand which parts of the template are regular classes and which are directives.虽然 Angular 确实支持指令的类选择器,但这个特性应该只在特殊情况下使用,因为它很难理解模板的哪些部分是常规类,哪些是指令。 This is why this syntax is tslint warning and not a compilation error.这就是为什么此语法是 tslint 警告而不是编译错误的原因。

If you insist on using this selector style, you can change the tslint config, or prefix the callsite in the code with tslint ignore comment, but you'll make your life and other's life easier if you stick to attribute selectors instead.如果您坚持使用这种选择器样式,您可以更改 tslint 配置,或者在代码中使用 tslint 忽略注释作为调用站点的前缀,但是如果您坚持使用属性选择器,您将让您和其他人的生活更轻松。

This is not very satisfying, but there seems no way around it.这不是很令人满意,但似乎没有办法解决。

In my case, the problem was the following array typing:就我而言,问题在于以下数组类型:

public dateFormats: Array<{ format: string, eq: string }> = [...];

Not using the generic syntax fixed the errors.不使用通用语法修复了错误。

I will definitely consider migrating from tslint to eslint as the support is discontinued when it comes to Angular CLI.我肯定会考虑从tslint迁移到eslint因为对 Angular CLI 的支持已停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM