0

I have an Aura parent component and an LWC child component. In the parent component helper I'd like to change an @api attribute of the child component.

I know how to find the child component using its aura:id.

My current solution is to bind the child component's attribute to an aura:attribute of the parent and then change the aura:attribute of the parent in the parent's helper. This works fine. However, I'd like to know how to change the child's attribute directly.

childComponent.setAttribute has not worked.

4
  • I dont think there is a way to do what you are describing. The way you are currently doing it is the best practice way Commented Jun 20, 2023 at 18:18
  • @BryanAnderson thanks. that seems so odd. setAttribute is a method that it seems normal to work with that. Commented Jun 20, 2023 at 18:22
  • setAttribute is an HTML standard, not something part of LWC or Aura Commented Jun 20, 2023 at 18:28
  • @BryanAnderson When you find the child component though, using aura:id, can't you call methods that are exposed using @api? How do you call a setter? Commented Jun 20, 2023 at 21:11

1 Answer 1

1

The child LWC is still exposed as a SecureComponent, so the solution is to simply call the SecureComponent#set method:

// helloWorldMsg.js
import { LightningElement, api } from 'lwc';

export default class HelloWorldMsg extends LightningElement {
    @api message;
}
<!-- helloWorldMsg.html -->
<template>
{message}
</template>
<!-- helloWorldMsgApp.app -->
<aura:application >
    <lightning:button label="Say Hello" onclick="{!c.click}" />
    <hr />
    <c:helloWorldMsg aura:id="hello" />

</aura:application>
({
    click: function(component, event, helper) {
        let hello = component.find("hello");
        hello.set("v.message", "Hello World!");
    }
})

Note the use of the value provider v to set the attribute.

2
  • @sfdxfox thanks. Is this not better practice than doing the binding? I can see that in some situations changing it one place is easier than changing it in many. But this isn’t that situation Commented Jun 20, 2023 at 23:53
  • @seekingPeace Two-way data binding is imperfect in Aura, which is why LWC doesn't have it. That said, either method works just fine in the usual sense. Use whichever method you feel is more appropriate for your component's design.
    – sfdcfox
    Commented Jun 21, 2023 at 17:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .