[SalesForce] LWC Modal With Dynamic HTML Content Slot

Has anyone gotten the modal example to work with having the content variable being HTML or a template file? I am trying to reuse the modal for two different views so I am trying to dynamically set the content in JS by importing a different template file, but it's display the raw string instead of HTML.

Example: trailheadapps/lwc-recipes/modal

Example:

import details from "./templates/details.html";

showModal(data, template) {

  this.modalHeader = data.customerName + " - " + data.recommendation;
  this.modalContent = template;

  const modal = this.template.querySelector("c-modal");
  modal.show();

}

Best Answer

Expressions are always interpreted as String in Markup - there is currently no functionality in LWC which allows to directly render html strings due to security principles which means you would be need to escape the html and insert it via javascript e. g. to the innerHTML attribute of the elements or similiar (which only works for simple html - if you would reference other components that would not work because they can`t dynamically be instantiated). But that is a bad practices because you should try to not be dependent on working in dom directly.

If you only having two views why not using a helper variable in your js and just conditionally render different slots for the modal (or using the render lifecycle method to return a whole different html template with other slot or similiar)? Slots are the way to pass custom HTML to components

Related Topic