Introduction

This LWC demoes how a parent access a property on a child component, but the child component uses a getter and a setter function to provide some custom logic.

You might need to offer a public property for a parent component to access it. But also, you might need to run some logic when the parent component is reading or writing in this property.

In this scenario, a public getter and setter functions are used instead of a public property.

<aside> 💡 If your prefer a full review of this concept check this section Setter functions

</aside>

<aside> 📂 You can find the parent LWC in this relative path force-app\\main\\default\\lwc\\apiSetterGetterand the child nested component here force-app\\main\\default\\lwc\\todoList

</aside>

In the following image you see that a parent component (in red) is hosting a child component to show a list of todos (in green). When the button in the parent component is pressed, the new to-do is added to the list and shown into the child component list.

The parent component access the list of todos using a property, but, instead of direct access to the variable, this is done through a pair of functions called getter and setter.

Untitled

Child component

The child Javascript declares the _todosarray as private, so, unnaccesible to the parent.

But a getter and setter public functions are provided to allow it. Those functions can run custom code when the assignment or the reading are performed.

In this concrete scenario, the setter function, executes the assignment over the array but also calls the filterTodosfunction to show only the proper priority to-dos based on the checkbox value selected.

...
filteredTodos = [];
_todos = []; // This property, even private, is accessible from the parent with the getter and setter functions
priorityFilter = false;

@api // Only annotate the getter function as a best practice 
get todos() {
    return this._todos;
}
set todos(value) {
    this._todos = value;
    this.filterTodos(); // When the value is set, this function is executed
}
...

Parent component

When the user introduces a new to-do task and presses the button to save it, the handler handleSaveis invoked.

In this handler, the todos property is updated, with the spread operator, adding the new task.