简体   繁体   中英

The conflict between angular directive selector and tslint

I am using angular 4 directive to define an angular attribute directive. 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)

在此处输入图片说明

But I got a tslint error as below:

tslint 错误

Is there any way to fix this error without disable the tslint rule?

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: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):

...
"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 . 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. This is why this syntax is tslint warning and not a compilation error.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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