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:
app/user/user.component.tsclass 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:
app/user/user.component.tsclass 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:
app/app.component.html<user-data name="john"></user-data>
And in the child component we will display the passed name on the screen:
app/user/user.component.html<p>{{ name }}</p>
Задание 1
Explain why the private property _name begins with an underscore.
Задание 2
Implement setters and getters for the product name and price, which will be passed down from the parent component.