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.
Attached are the screenshots.
The delete button is present in child component and on click deletes the content of the input field.Code logic:
Comments
Post a Comment