New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Monday, 22 June 2020

LWC Cheat Sheet


Wire

JavaScript Find method -

var age = 17;
function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(ageVal => {
   return ageVal >= age;
  });
}

Calling child LWC method from parent -

const child = this.template.querySelector('c-public-method-child');
console.log(JSON.stringify(child));
child.changeSelection(this.city);

Constructor should have super in LWC js -

constructor() {
 super();
 console.log('Parent > Constructor.');
}

Importing and rendering multiple templates in LWC js -

import template1 from './lifecycleChild.html';
import template2 from './template2.html';
render() {
 console.log('Child > render.');
 return this.showTemplate2 ? template2 : template2;
}

CustomEvent firing from child to the parent

//Firing the event from the child component 
var cusEvt = new CustomEvent('mychildevent',{detail:'I am the message from child to parent.',bubbles:true});
this.dispatchEvent(cusEvt);

//Approach1: Handling the event from parent UI -
[c-child onmychildevent={handleChildEvent}][/c-child]
Note: handleChildEvent is the method in parent
handleChildEvent(event) { console.log(event.detail); }

//Approach2: Handling the event from parent JS -
constructor() {
 super();
 console.log('constructor');
 this.template.addEventListener('mychildevent',this.handleChildEvent.bind(this));
}
Note: When addEventListener is used "bubble:true" should be there in CustomEvent

Pubsub: Application Event Handling -

Download pubsub repository.

Firing the event -

  import {fireEvent} from 'c/pubsub';
  import { CurrentPageReference } from 'lightning/navigation';

  @wire(CurrentPageReference) 
  pageRef;
  
  handleClick() {
   debugger;
   fireEvent(this.pageRef,'parent2event','I am the event firing from parent2 component.');
   //Note: Event Name should be all in small characters and should not have special characters
  }
 

Handling the event -

  import {registerListener,unregisterAllListeners} from 'c/pubsub';
  import { CurrentPageReference } from 'lightning/navigation';
  
  @wire(CurrentPageReference) 
  pageRef;
  
  connectedCallback() {
   console.log('connectedCallback');
   registerListener('parent2event',this.handleAppEvent,this);
  }
  disconnectedCallback() {
   console.log('disconnectedCallback');
   unregisterAllListeners(this);
  }
  handleAppEvent(payload) {
   console.log('***payload: '+payload);
  }
 

Reusable javaScript -

Utility.js -

  const add = function(num1,num2) {
   return num1 + num2;
  }
  const substract = function(num1,num2) {
   return num1 - num2;
  }
  const multiply = function(num1,num2) {
   return num1 * num2;
  }
  const divide = function(num1,num2) {
   return num1 / num2;
  }

  export {
   add,
   substract,
   multiply,
   divide
  }
 

calling reusable js functions -

  import {add,substract,multiply,divide} from 'c/utility';
  
  constructor() {
   super();
   console.log('add: ',add(200,100));
   console.log('sub: ',substract(200,100));
   console.log('mul: ',multiply(200,100));
   console.log(`Div: ${divide(200,100)}`);
  }
 

LDS to get and create records -

  import { LightningElement, track, wire } from 'lwc';
  import {createRecord,getRecord} from 'lightning/uiRecordApi'

  const fieldsArray = ['Contact.FirstName','Contact.LastName','Contact.Email','Contact.MobilePhone'];
  export default class ContactForm extends LightningElement {   

   @track recordId;

   @wire(getRecord,{recordId:"$recordId", fields: fieldsArray})
   contact;


   firstNameChangeHandler(event) {
    this.firstName = event.target.value;
   }
   lastNameChangeHandler(event) {
    this.lastName = event.target.value;
   }
   emailChangeHandler(event) {
    this.email = event.target.value;
   }
   mobileChangeHandler(event) {
    this.mobile = event.target.value;
   }
   
   createContact() {
    debugger;
    //Field API Names along with the data
    const fields = {
     "FirstName" : this.firstName,
     "LastName" : this.lastName,
     "Email" : this.email,
     "MobilePhone" : this.mobile
    };

    var recordInput = {
     apiName : "Contact", fields
    };
     
    //Using javaScript promise concept
    createRecord(recordInput).then(response => {
     console.log('Record Id: '+response.id);
     this.recordId = response.id;
    }).catch(error => {
     console.log('Error Object: '+JSON.stringify(error));
     console.log('Error Message: '+error.body.message);
    });

   }

   get retFirstName() {
    debugger;
    console.log('contact: '+JSON.stringify(this.contact));
    if(this.contact.data) {
     return this.contact.data.fields.FirstName.value;
    }
    return undefined;
   }

   get retLastName() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.LastName.value;
    }
    return undefined;
   }

   get retEmail() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.Email.value;
    }
    return undefined;
   }

   get retMobile() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.MobilePhone.value;
    }
    return undefined;
   }
   
   
  }
 

Imperative Apex Call, Toast Message and Navigation Service

Apex Class - Js - Template -

36 comments:

  1. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra.
    360DigiTMG data analytics course

    ReplyDelete
    Replies
    1. Great Article Cloud Computing Projects

      Networking Projects

      Final Year Projects for CSE

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. You should talk it's shocking. Your blog survey would extend your visitors. I was fulfilled to find this site.I expected to thank you for this phenomenal read!!
    data science certification

    ReplyDelete
  3. I think I have never watched such online diaries ever that has absolute things with all nuances which I need. So thoughtfully update this ever for us.
    difference between analysis and analytics

    ReplyDelete
  4. It's acceptable to check this sort of site. I figure I would such a great amount from you.
    data science course in noida

    ReplyDelete
  5. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.data science course in Hyderabad

    ReplyDelete
  6. Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work.data science course in Hyderabad

    ReplyDelete
  7. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Data Science course in Hyderabad

    ReplyDelete
  8. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    data science training in bangalore

    ReplyDelete
  9. Astounding Blog! I might want to thank for the endeavors you have made recorded as a hard copy this post. I am trusting a similar best work from you later on too. I needed to thank you for this sites! Much obliged for sharing. Extraordinary sites!
    data scientist course in hyderabad

    ReplyDelete
  10. Really wonderful blog completely enjoyed reading and learning to gain the vast knowledge. Eventually, this blog helps in developing certain skills which in turn helpful in implementing those skills. Thanking the blogger for delivering such a beautiful content and keep posting the contents in upcoming days.

    data science certification in bangalore

    ReplyDelete
  11. Hey, great blog, but I don’t understand how to add your site in my rss reader. Can you Help me please?
    data scientist training and placement in hyderabad

    ReplyDelete
  12. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest posts. I will visit your blog regularly for Some latest posts.
    data scientist course in hyderabad

    ReplyDelete
  13. Thanks for posting the best information and the blog is very good.digital marketing institute in hyderabad

    ReplyDelete
  14. Thanks for posting the best information and the blog is very important.artificial intelligence course in hyderabad

    ReplyDelete
  15. I was actually browsing the internet for certain information, accidentally came across your blog found it to be very impressive. I am elated to go with the information you have provided on this blog, eventually, it helps the readers whoever goes through this blog. Hoping you continue the spirit to inspire the readers and amaze them with your fabulous content.

    Data Science Course in Faridabad

    ReplyDelete
  16. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara

    ReplyDelete
  17. It is extremely nice to see the greatest details presented in an easy and understanding manner.
    data scientist certification malaysia

    ReplyDelete
  18. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!cloud computing course in patna

    ReplyDelete
  19. First You got a great blog .I will be interested in more similar topics.I commend you for your excellent report on the knowledge that you have shared in this blog.

    digital marketing training in hyderabad
    free digital marketing course in hyderabad

    ReplyDelete
  20. Thanks for posting the best information and the blog is very good.data science in kolkata

    ReplyDelete
  21. Thanks for posting the best information and the blog is very good. business analytics course in kolkata

    ReplyDelete
  22. Thanks for posting the best information and the blog is very good. ethical hacking training in kolkata

    ReplyDelete
  23. Thanks for posting the best information and the blog is very good.data science course in ahmedabad

    ReplyDelete
  24. Thanks for posting the best information and the blog is very good.data science training in ahmedabad

    ReplyDelete
  25. Thanks for posting the best information and the blog is very good.ai courses in kolkata

    ReplyDelete
  26. Thanks for posting the best information and the blog is very good.cyber security colleges in kolkata

    ReplyDelete
  27. Thanks for posting the best information and the blog is very good.ethical hacking institute in ahmedabad

    ReplyDelete
  28. Thanks for posting the best information and the blog is very good.machine learning course in kolkata

    ReplyDelete
  29. Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post .
    data science online training in hyderabad

    ReplyDelete
  30. Impressive. Your story always bring hope and new energy. Keep up the good work. Data Science Training in Chennai

    ReplyDelete
  31. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data analytics course in varanasi

    ReplyDelete
  32. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science course in varanasi

    ReplyDelete
  33. He's really nice and mean. it's a really cool blog. The link is a very useful thing. You have really helped a lot of people who visit the blog and give them useful information. Data Science Training in Dombivli

    ReplyDelete