no-unused-variable TSLint rule does not work with private @HostBinding

1.2k views Asked by At

In my TSLint file, I have:

"no-unused-variable": true

In my components, I sometimes have:

// tslint:disable-next-line:no-unused-variable
@HostBinding('class') private classes = 'my-theme';

Because classes is private, TSLint complains, so I have to disable TSLint everytime.

I do not want to make @HostBinding public because of encapsulation.

What is the recommended way to solve this problem?

2

There are 2 answers

0
Dolan On BEST ANSWER

After some research, the solution is to simply make it public

@HostBinding('class') public classes = 'my-theme';

This is because from Angular's perspective, it accesses the component, something like component.classes. Therefore, semantically, it is public. It's the same reason why @Input should be public even if you don't use it in the template.

Sources:

https://stackoverflow.com/a/38469573/3481582

0
Gokhan Kurt On

You have two options, as far as I know.

1 - Use protected. Self explaining:

@HostBinding('class') protected classes = 'my-theme';

2 - Use ignore-pattern. The variable and import names matching the specified pattern will be ignored by this rule according to here. The pattern is a regex and ^_ means any string starting with _.

tslint.json:

...
"no-unused-variable": [true, {"ignore-pattern": "^_"}]
...

component:

@HostBinding('class') private _classes = 'my-theme';

Bonus

If your variable is readonly, you can do one of these too. It will not prevent the tslint error but it will prevent modifying the variable accidentally if that is what worries you about encapsulation.

@HostBinding('class') private readonly classes = 'my-theme';
@HostBinding('class') private get classes() { return 'my-theme'; }