Custom popup actions per feature attribute

It is possible to customize Popup and PopupTemplate actions per feature attribute.

This sample demonstrates how to format custom actions specifically per selected feature. It uses a Popup and a PopupTemplate. Although actions can be added via the actions property on either the Popup or PopupTemplate, the actions in this sample are specifically set within the featurelayer's popupTemplate.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
popupTemplate: {
  actions: [
    {
      id: "find-brewery",
      image: "beer.png",
      title: "Brewery Info"
    }
  ];
}

Actions are styled by either using the class or image property. If using class, you must use an icon font. If using image, you must provide a valid URL to an image that will be used as a background-image for the action. In this specific example, an image is used to indicate the action button.

How it works

First, watch for the Popup's selectedFeature property. Next, set the action's visible property to true if the feature's website value isn't null, otherwise set it to false.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
reactiveUtils.watch(
  () => view.popup.selectedFeature,
  (graphic) => {
    if (graphic) {
      // Set the action's visible property to true if the 'website' field value is not null, otherwise set it to false
      const graphicTemplate = graphic.getEffectivePopupTemplate();
      graphicTemplate.actions.items[0].visible = graphic.attributes.website ? true : false;
    }
  }
);

The PopupViewModel's trigger-action is fired and then checks for the action ID. In this case, it's listening for an ID called find-brewery.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
reactiveUtils.on(
  () => popup.viewModel,
  "trigger-action",
  (event) => {
    if (event.action.id === "find-brewery") {
    // do something
  }
});

Next, it grabs the attributes of the selected feature. We don't need all of them, so in this example we explicitly grab the attribute with the name website and store it in a new variable called info.

Use dark colors for code blocksCopy
1
2
3
const attributes = popup.viewModel.selectedFeature.attributes;
// Get the 'website' field attribute
const info = attributes.website;

After this, we check to make certain this value is not null. If not, some string manipulation is performed and the URL value stored within the website field is opened up in a new browser window. Otherwise, a message is displayed in the console window.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
{
  // Make sure the 'website' attribute value is not null
  if (info) {
    // Open up a new browser using the URL value in the 'website' field
    window.open(info.trim());
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.