'"private" and "public" in Angular component
If I don’t add private before foo, loadBar, andtext, I believe they are public by default.
export class RandomComponent {
@Input() foo: string;
@Output() loadBar = new EventEmitter();
text: string;
}
Is there any use case when they are public in the component?
For encapsulation/security reason, should I always add private for all of them like below?
export class RandomComponent {
@Input() private foo: string;
@Output() private loadBar = new EventEmitter();
private text: string;
}
Thanks
Solution 1:[1]
@drewmoore provides a good answer in that private/public boils down to intent. But there are a few more things to consider when using injected private values:
- Both typescript (noUnusedLocals) and tslint (no-unused-variable) will report errors if you use
@Import() private foo, orconstructor(private foo) {}, and only usefooin your template - AOT wont work:
If we want to emit TypeScript as output of the AoT compilation process we must make sure we access only public fields in the templates of our components**
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucas |
