I want to retrieve(get) the data of another component.
What I want to do is: Get the data from 'iHaveData_cmp' component, and show it in 'iWantData_cmp' component.
I've tried this.template.querySelector(c-target-component).MethodToGetTheData();
to call the @api method from the target component, but it didn't work. (it constantly failed to get the target component itself)
Do I have to use MessageChannel or binding those two components as parent-child is the only way to accomplish this?
What I tried so far:
iHaveData_cmp.html
<template>
<div>
<lightning-input label="This is the data" value={data} read-only="true"></lightning-input>
</div>
</template>
iHaveData_cmp.js
import { LightningElement, api } from 'lwc';
export default class IHaveData_cmp extends LightningElement {
data = 1000;
@api passData(){
return this.data;
}
}
iWantData_cmp.html
<template>
<div>
<lightning-input label="I show the data that I received" value={getData} read-only="true"></lightning-input>
</div>
</template>
iWantData_cmp.js
import { LightningElement } from 'lwc';
export default class IWantData_cmp extends LightningElement {
get getData(){
let result = this.template.querySelector('c-i-have-data_cmp').passData();
return result;
// returns an error message below:
// iWantData_cmp:13878 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'passData')
// at get getData [as getData] (iWantData_cmp:13878:70)
// at tmpl$l (iWantData_cmp:13862:25)
// at app:2703:23
// at ReactiveObserver.observe (app:2902:9)
// at isUpdatingTemplate (app:2654:11)
// at runWithBoundaryProtection (app:5339:7)
// at evaluateTemplate (app:2639:5)
// at invokeComponentRenderMethod (app:2816:41)
// at renderComponent (app:3013:20)
// at rehydrate (app:5030:24)
}
}
c-target-component
should be enclosed in quote:this.template.querySelector('c-target-component')
. Keep in mind that hiding too many info will reduce the chance of getting the proper help.