Passing data to a child component setter in Angular
It is possible to make the data from the parent component go to the setter of a private property. Let's look at an example. Let's say we have a private property with a setter and a getter:
class UserComponent {
private _name: string = '';
set name(name: string) {
if (name.length < 3) {
this._name = name;
} else {
console.log('error');
}
}
get age() {
return this._userAge;
}
}
For example, let's make an age setter, in which we will implement the check of the transferred data. We will also make a getter to display the user properties:
class UserComponent {
private _name: string = '';
@Input()
set name(name: string) {
if (name.length > 3) {
this._name = name;
} else {
console.log('error');
}
}
get name() {
return this._name;
}
}
Now let's pass data from the parent component to the child:
<user-data name="john"></user-data>
And in the child component we will display the passed name on the screen:
<p>{{ name }}</p>
Explain why the private property _name begins with an underscore.
Implement setters and getters for the product name and price, which will be passed down from the parent component.