4

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?

Dolan
  • 1,519
  • 4
  • 16
  • 36
  • Is it a bug that it thinks it is unused? If you are only using it in the constructor you don’t need the word `private`. I think tslint will complain when you’re making something an instance variable and only using it in the constructor. – Pace Feb 24 '19 at 01:14

2 Answers2

5

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'; }
Gokhan Kurt
  • 8,239
  • 1
  • 27
  • 51
0

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

Dolan
  • 1,519
  • 4
  • 16
  • 36