[英]no-unused-variable TSLint rule does not work with private @HostBinding
In my TSLint file, I have: 在我的TSLint文件中,我有:
"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. 因为
classes
是私有的,所以TSLint抱怨,所以我必须每次都禁用TSLint。
I do not want to make @HostBinding
public because of encapsulation. 我不想做
@HostBinding
因为封装的公众。
What is the recommended way to solve this problem? 解决此问题的推荐方法是什么?
You have two options, as far as I know. 据我所知,你有两种选择。
1 - Use protected
. 1 - 使用
protected
。 Self explaining: 自我解释:
@HostBinding('class') protected classes = 'my-theme';
2 - Use ignore-pattern
. 2 - 使用
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: 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.
它不会阻止tslint错误但它会阻止意外修改变量,如果这是你担心的封装。
@HostBinding('class') private readonly classes = 'my-theme';
@HostBinding('class') private get classes() { return 'my-theme'; }
After some research, the solution is to simply make it public
经过一番研究,解决方案就是将其
public
@HostBinding('class') public classes = 'my-theme';
This is because from Angular's perspective, it accesses the component, something like component.classes
. 这是因为从Angular的角度来看,它访问组件,类似于
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. 这就是为什么即使你不在模板中使用
@Input
应该公开的原因。
Sources: 资料来源:
https://stackoverflow.com/a/38469573/3481582 https://stackoverflow.com/a/38469573/3481582
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.