3

As for my analysis Not able to render dynamic Lightning Web Component Dynamic creation of the Lightning Web Components is not yet supported.

Can someone suggest a better approach to render the input field based on the type. Below is my Example scenario

I have a situation that the user can choose any fields on the Object. Based on the field type I need to render the input box.

Approach 1 :

<template if:true={isPhone}>
  phone input
</template>
<template if:true={isEmail}>
  Email input
</template>
'
'
' and more.....

This approach drawback is all the template:if gets called, for one type

Approach 2:

Render Template based on the type.

 import { LightningElement, track  } from 'lwc';
   import inputPhone from './inputPhone.html';
   import inputEmail from './inputEmail.html';

   render() {
        return isPhone ? inputPhone : inputEmail;
    }

I dint tried this approach I wondering this will work or not?

Can someone please share your thoughts on this? Thanks in advance.

1 Answer 1

2

Both of these approaches you have described should work fine.

The 1st approach is illustrated in the salesforce lightning base components recipe here for outputfield.

This approach is one i would prefer if i am going to reuse the individual components.Using composition allows one to loose couple components and one gets maximum reusability of child components.

The second approach is essentially when you have no reusability of the templates across other components. You are building one single component. An example of such component is shown here

For your use case option 1 looks more better approach since you might use the phone and email component individually as well with other components

5
  • 2
    I think both the approaches are equally reusable. Only difference is in 1st approach the child components like phone component can be used individually. Commented Dec 22, 2019 at 6:24
  • That's what the answer conveys ! Both approaches are viable but in first you use proper composition so child components can be reused ! Commented Dec 22, 2019 at 8:25
  • Hi Mohith, AFAIK, it isn't possible to nominate templates by their path only (at runtime so the templates can be added later) in approach 2. Is that a correct assumption?
    – Keith C
    Commented Dec 22, 2019 at 9:36
  • You mean dynamic imports ? I don't think at this point any dynamic behavior is supported. Commented Dec 22, 2019 at 9:55
  • Thanks ....@mohith, keith,salesforcesas
    – vignesh
    Commented Dec 22, 2019 at 16:36

You must log in to answer this question.

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