Salesforce Fact #351 | Call reusable child component's public method from parent in LWC

Suppose we have a LWC component which has been used multiple times as child in the same component. It is like the component has been reused. Now, the component has a method which does some processing on the value associated with that component. But what if we want to call it from the parent component. Well, well!! you just need to annotate the method in child component with @api. Now, you can call this method straight from the parent component.

In this simple example, we have a child component which contains text input field and a delete button to remove the content of that input field. Now, the same component has been used twice in the parent component. Now, if we want to call the method associated to the particular child component reference, we can make use of some data-id attribute to uniquely identify the component reference, template.querySelector() and call the method related to that child component accordingly. For this we need to annotate the child component method with @api.

Reference: https://salesforce.stackexchange.com/questions/317092/select-child-component-in-lwc-when-it-is-present-multiple-times

Attached are the screenshots.

The delete button is present in child component and on click deletes the content of the input field.





Now, from parent component we can call the public method of the associated child by using @api annotation.



Code logic:







Comments

Popular posts from this blog

Salesforce Fact #192 | Call batch apex from flow

Salesforce Fact #457 | Get current user role name in flow