LWC – Display List of Opportunities on Click Event

I want to display the list of opportunities when a button is clicked. For some reason, my code does not work.

Apex class:

public with sharing class OpportunityController {
   
   @AuraEnabled(Cacheable = true)
    public static List<Opportunity> getAllStages(){
       return [Select Name, StageName from Opportunity order by Name];
    }
}

Parent component HTML:

<template>
    <lightning-card title="Opportunities">
        <div class="slds-var-m-around_medium">
            <lightning-button label="All" onclick={allStages}></lightning-button>
        </div>

        <template for:each={oppresult} for:item="rslt">
            <c-wired-opportunities key={rslt} ></c-wired-opportunities>
        </template>

    </lightning-card>
</template>

Child component HTML:

<template>
        <div class="slds-var-m-around_medium">
            <h4>{rslt.Name}</h4>
            <h4>{rslt.StageName}</h4>
        </div>
</template>

Parent component JS:

import { LightningElement, api, wire, track } from 'lwc';
import getAllStages from '@salesforce/apex/OpportunityController.getAllStages';

const COLUMNS = [
    {label: 'Name', fieldName: 'Name', type:'text'},
    {label: 'Stage', fieldName: 'StageName', type:'text'}
];

export default class WireDemo extends LightningElement {
    columns = COLUMNS;

    oppresult;
    errorMsg;

    allStages(){
        getAllStages()
        .then(result =>{
            this.oppresult = result;
        })
        .catch(error =>{
            this.errorMsg = error;
        })
    }
}

Best Answer

I don't see any error in your code for Parent Component. Make sure you have marked the Opportunity public variable with @api decorator in child. Also the parameter name should be same as public property while passing from Parent to child. Check the below code and see if you are missing anything in your code.

Parent HTML

.....................
.....................
<template for:each={oppresult} for:item="rslt">
    <c-wired-opportunities opp={rslt} key={rslt.Id}></c-wired-opportunities>
</template>
.....................
.....................

Child JS

import { LightningElement,api } from 'lwc';

export default class WiredOpportunities extends LightningElement {
    @api opp;
}

Child HTML

<template>
    <div class="slds-var-m-around_medium">
        <h4>{opp.Name}</h4>
        <h4>{opp.StageName}</h4>
    </div>
</template>
Related Topic