Stack Overflow Asked by NatoBoram on December 16, 2021
Let’s say, in an Angular component, I receive a parameter from its parent.
export class SomethingComponent implements OnChanges {
@Input() delay: number;
}
Is it good practice, acceptable, or better to mark it as private
or readonly
?
export class SomethingComponent implements OnChanges {
@Input() private readonly delay: number;
}
What’s the technical difference?
From a purely technical standpoint, neither actually matter at runtime as both do not exist in Javascript. These constructs are only present in Typescript to aid the developers.
Here's some example Typescript:
class Car {
private ownerName: string;
readonly vehicleIdNumber: string;
mileage: number;
}
let car = new Car();
//typescript compilation error:
// Property 'ownerName' is private and only accessible within class 'Car'.
car.ownerName = "test";
//typescript compilation error:
// Cannot assign to 'vehicleIdNumber' because it is a read-only property.
car.vehicleIdNumber = "543798";
//No error here!
car.mileage = 10000;
When this is compiled to Javascript, those access modifiers go away and you're free to use those attributes are you wish. Here's what the resulting Javascript would look like.
class Car {
}
let car = new Car();
car.ownerName = "test";
car.vehicleIdNumber = "543798";
car.mileage = 10000;
From Angulars perspective, private
or readonly
on an @Input()
property doesn't really make sense.
Private members are typically only accessible within the body of the class it's declared in. Since you're accessing them outside the class in another components template, you're violating this rule.
Readonly members are typically not allowed to be assigned to after the constructor exits, and in Angular the @Input()
attributes are actually set after the constructor but before ngOnInit()
.
Answered by spots on December 16, 2021
The private
keyword is just meant to state an intention at compile time as a way to encapsulate there is no difference at runtime. And the conveyed intention is that the said variable or property or method should not be accessed by any other class or component. From a security point of view there is no inherent benefit to doing this.
So answering your question, it is okay to mark it as private as long as your intent is to signal for coder's understanding while they are trying to access it from another place in application.
Answered by ijaspreetbhatti on December 16, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP