简体   繁体   中英

Lightning Web Component setting dynamic style not working as expected

I'm currently trying to render a specific class across two lightning-badge components that is suppose to change both badges from inverse to success, but am getting this instead:

呈现的 html

When the value on the left badge equals the value on the right (so in this case both are 3), they should both be green, otherwise they should both be grey. They should never be seperate colours. The value on the left increases as the user saves a record and is checked on status of "Completed". For some reason only the class on the second badge is being updated with the new class that includes slds-theme_success. I may be missing something small, but just haven't been able to figure it out. Please see code below:

 badgeClass = "slds-badge_inverse slds-var-m-horizontal_x-small slds-col"; get patientsCompleted() { if(this.records) { let completedArr = this.records.filter(value => value.fields.Status__c.value == "Completed"); if(completedArr.length === this.patientsTotal) { this.badgeClass = "slds-badge_inverse slds-theme_success slds-var-m-horizontal_x-small slds-col"; } return completedArr.length; } }; get patientsTotal(){ if(this.records) { return this.records.length; } };
 <span class="slds-col_bump-left"> <div class="slds-grid slds-gutters"> <lightning-badge class={badgeClass} label={patientsCompleted}></lightning-badge> <div class="slds-col"> of </div> <lightning-badge class={badgeClass} label={patientsTotal}></lightning-badge> </div> </span>

Have you tried moving badgeClass to a getter? Something like this:

get patientsCompleted() {
  if(this.records) {
    let completedArr = this.records.filter(value => value.fields.Status__c.value == "Completed");
    // No longer needed
    // if(completedArr.length === this.patientsTotal) {
    //     this.badgeClass = "slds-badge_inverse slds-theme_success slds-var-m-horizontal_x-small slds-col";
    // }
    return completedArr.length;
    }
};

get patientsTotal(){
  if(this.records) {
    return this.records.length;
  }
};

get badgeClass() {
  let baseClass = "slds-badge_inverse slds-var-m-horizontal_x-small slds-col";
  return this.patientsCompleted === this.patientsTotal ? `${baseClass} slds-theme_success` : `${baseClass}`
}

I suspect LWC field tracking has some precautionary mechanism and didn't trigger the update.

I am not sure but perhaps if 0 records are available you want the badges to remain gray? In that case include this.patientsTotal > 0 in the get badgeClass() {...} .

Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM