Concepts / Building Search UI / Customize an existing widget
Jun. 28, 2019

Customize an Existing Widget

You are reading the documentation for Angular InstantSearch v3, which is in beta. You can find the v2 documentation here.

Highlight your search results

Search is all about helping users understand the results. This is especially true when using text-based search. When a user types a query in the search box, the results must show why the results are matching the query. That’s why Algolia implements a powerful highlight that lets you display the matching parts of text attributes in the results.

Highlighting is based on the results and you will need to make a custom Hit in order to use the Highlighter. The ais-highlight widgets take two props:

  • attribute: the path to the highlighted attribute of the hit (which can be either a string or an array of strings)
  • hit: a single result object

Notes:

  • Use the ais-highlight widget when you want to display the regular value of an attribute.
  • The snippet widget, available in other flavors, is not available in Angular Instantsearch. It is meant to display the snippet version of an attribute.

Here is an example in which we leverage the directive ng-template of the Hit widget. In our results we have a name field that is highlighted. In these examples we use the mark tag to highlight. This is a tag specially made for highlighting pieces of text.

1
2
3
4
5
6
7
<ais-hits>
  <ng-template let-hits="hits">
    <div *ngFor="let hit of hits">
      <ais-highlight attribute="name" [hit]="hit"></ais-highlight>
    </div>
  </ng-template>
</ais-hits>

Style your widgets

All widgets are shipped with fixed CSS class names.

The format for those class names is ais-NameOfWidget-element--modifier. We are following the naming convention defined by SUIT CSS.

The different class names used by each widget are described on their respective documentation pages. You can also inspect the underlying DOM and style accordingly.

Loading the theme

We do not load any CSS into your page automatically but we provide two themes that you can load manually:

  • reset.css
  • algolia.css

We strongly recommend that you use at least reset.css in order to avoid visual side effects caused by the new HTML semantics.

The reset theme CSS is included within the algolia CSS, so there is no need to import it separately when you are using the algolia theme.

Via CDN

The themes are available on jsDelivr:

unminified:

minified:

You can either copy paste the content into your own app or use a direct link to jsDelivr:

1
2
3
4
<!-- Include only the reset -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@7.3.1/themes/reset-min.css" integrity="sha256-t2ATOGCtAIZNnzER679jwcFcKYfLlw01gli6F6oszk8=" crossorigin="anonymous">
<!-- or include the full Algolia theme -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@7.3.1/themes/algolia-min.css" integrity="sha256-HB49n/BZjuqiCtQQf49OdZn63XuKFaxcIHWf0HNKte8=" crossorigin="anonymous">

Via Yarn (npm) & Angular CLI

instantsearch.css has been installed as part of Angular Instantsearch dependencies. To load the theme, add it to the apps > styles array of your angular.json configuration file:

1
2
3
4
5
6
{
  "styles": [
    "node_modules/instantsearch.css/themes/algolia.css",
    "styles.css"
  ]
}

Or only the reset:

1
2
3
4
5
6
{
  "styles": [
    "node_modules/instantsearch.css/themes/reset.css",
    "styles.css"
  ]
}

Translate your widgets

Angular InstantSearch doesn’t have a dedicated API for translating text, but every component exposes attributes to override. For example, in ais-refinement-list:

1
2
3
4
5
6
7
<ais-refinement-list
  attribute="brand"
  operator="or"
  showMoreLabel="More please"
  showLessLabel="Less please"
>
</ais-refinement-list>

Templating

Some components of Angular InstantSearch support templating via ng-template directive. For example in ais-hits:

1
2
3
4
5
<ais-stats>
  <ng-template let-state="state">
    {{state.nbHits}} results found in {{state.processingTimeMS}}ms.
  </ng-template>
</ais-stats>

Modify the list of items in widgets

Angular InstantSearch provides two API’s for manipulating lists:

  • sortBy, which is the most straightforward API and obviously limited to sorting
  • transformItems, which is the most flexible solution but it requires more involvement on your side

The transformItems prop is a function that takes the whole list of items as a parameter and expects to receive in return another array of items. Most of the examples in this guide will use this API.

Sorting

Using sortBy

1
2
3
4
5
6
<ais-refinement-list
  attribute="brand"
  operator="or"
  [sortBy]="['isRefined', 'name:asc']"
>
</ais-refinement-list>

Using transformItems

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component({
  template: `
    <ais-refinement-list
      // ...
      [transformItems]="transformItems"
    ></ais-refinement-list>
  `,
})
export class AppComponent {
  transformItems(items) {
    return items.sort((a,b) => a.value.localeCompare(b.value))
  }
}

Filtering

In this example, we filter out items when the count is lower than 150:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component({
  template: `
    <ais-refinement-list
      // ...
      [transformItems]="transformItems"
    ></ais-refinement-list>
  `,
})
export class AppComponent {
  transformItems(items) {
    return items.filter(item => item.count >= 150)
  }
}

Add manual values

By default, the values in a ais-refinement-list or a ais-menu are dynamic. This means that the values are updated with the context of the search. Most of the time this is the expected behavior, but in some cases you may want to have a static list of values that never change.

In this example, we use a static list of values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component({
  template: `
    <ais-refinement-list
      // ...
      [transformItems]="getStaticValues"
    ></ais-refinement-list>
  `,
})
export class AppComponent {
  getStaticValues(items) {
    const staticValues = ['Cell Phones', 'Unlocked Cell Phones'];
    return staticValues.map(value => {
      const item = items.find(item => item.label === value);
      return item || {
        label: value,
        value,
        count: 0,
        isRefined: false,
        highlighted: value,
      };
    });
  }
}

Searching long lists

Use the searchable prop to add a search box to supported widgets:

1
2
3
4
<ais-refinement-list
  attribute="categories"
  [searchable]="true"
/>

Apply default value to widgets

A question that comes up frequently is “how do I instantiate a ais-refinement-list widget with a pre-selected item?”. For this use case, you can use the ais-configure widget.

The following example instantiates a search page with a default query of “apple” and will show a category menu where the item “Cell Phones” is already selected:

1
2
3
4
5
6
7
8
9
10
11
<ais-instantsearch [config]="...">
  <ais-configure [searchParameters]="{
    query: 'apple',
    disjunctiveFacetsRefinements: {
      categories: ['Cell Phones'],
    },
  }"></ais-configure>
  <ais-refinement-list [attribute]="categories"></ais-refinement-list>
  <ais-search-box></ais-search-box>
  <ais-hits></ais-hits>
</ais-instantsearch>

How to provide search parameters

Algolia has a wide range of parameters. If one of the parameters you want to use is not covered by any widget, then you should use the ais-configure widget.

Here’s an example configuring the number of results per page:

1
2
3
4
<ais-instantsearch [config]="...">
  <ais-configure [searchParameters]="{ hitsPerPage: 3 }"></ais-configure>
  <ais-hits></ais-hits>
</ais-instantsearch>

Dynamic update of search parameters

Updating the props of the ais-configure widget will dynamically change the search parameters and trigger a new search.

Filter your results in a way that is not covered by any widget

Our widgets already provide a lot of different ways to filter your results but sometimes you might have more complicated use cases that require the usage of the filters search parameter.

Don’t use filters on a attribute already used with a widget, it will conflict.

1
<ais-configure [searchParameters]="{ filters: 'NOT categories:"Cell Phones"' }"></ais-configure>

Customize the complete UI of the widgets

Extending Angular InstantSearch widgets is the second layer of our API. Read about the two others possibilities in the What is InstantSearch? guide.

When do I need to extend widgets?

By extending widgets we mean being able to redefine the rendering output of an existing widget. Let’s say you want to render the Menu widget as an HTML select element. To do this you need to extend the Menu widget.

Here are some common examples that require the usage of the connectors API:

  • When you want to display our widgets using another UI library
  • When you want to have full control on the rendering without having to reimplement business logic
  • As soon as you hit a feature wall using our default widgets

How widgets are built

Angular InstantSearch widgets are built in two parts:

  1. business logic code
  2. rendering code

The business logic is what we call connectors. Those connectors are provided by InstantSearch.js and their interfaces are exposed through the BaseWidget class.

Connectors render API

We try to share as much of a common API between all connectors, so that once you know how to use one connector, you can use them all.

BaseWidget class

The BaseWidget class helps you create new widgets using the InstantSearch.js connectors with Angular.

It encapsulates the logic to maintain the state of the widget in sync with the search and handles the initialization and the disposal of the widget on Angular life cycle hooks. Let’s go step by step on how to write a custom widget using the BaseWidget class.

Extending widget example

In this example we will create a new custom widget using the BaseWidget class and the menu InstantSearch.js connector. The default ais-menu widget renders a list of links, but we would like to render it as a <select> element instead.

1. Extend the BaseWidget class

First of all, you will need to write some boilerplate code. Let’s create an MenuSelect Angular component that:

  • extends the BaseWidget class
  • references the <ais-instantsearch> parent component instance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { Component, Inject, forwardRef } from '@angular/core';
import { BaseWidget, NgAisInstantSearch } from 'angular-instantsearch';

@Component({
  selector: 'ais-menu-select',
  template: '<p>It works!</p>'
})
export class MenuSelect extends BaseWidget {
  constructor(
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchParent
  ) {
    super('MenuSelect');
  }
}

We have the first code needed for our MenuSelect widget, let’s move on to the connector part!

2. Inject the menu connector

The BaseWidget class has a method called createWidget() which takes as first parameter the connector to use and as second parameters an object of options for this connector.

In our case, we will use the menu connector which accepts multiple options. For simplicity we will only use the attributeName option which is the only one mandatory. (The attributeName is the name of the attribute for faceting)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Component, Inject, forwardRef, OnInit } from '@angular/core';
import { BaseWidget, NgAisInstantSearch } from 'angular-instantsearch';
import { connectMenu } from 'instantsearch.js/es/connectors';

@Component({
  selector: 'ais-menu-select',
  template: '<p>It works!</p>'
})
export class MenuSelect extends BaseWidget implements OnInit {
  constructor(
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchParent
  ) {
    super('MenuSelect');
  }

  public ngOnInit() {
    this.createWidget(connectMenu, { attributeName: 'categories' });
    super.ngOnInit();
  }
}

That’s it, your widget is connected to InstantSearch.js and the state of the search itself! Now let’s update the rendering of this widget

3. Render from the state

Your component instance has access to a property this.state which holds the rendering options of the widget. Most connectors expose into the state the same properties:

  • items[]: array of items to display, for example the brands list of a custom Refinement List. Every extended widget displaying a list gets an items property to the data passed to its render function.
  • refine(value|item.value): will refine the current state of the widget. Examples include: updating the query for a custom SearchBox or selecting a new item in a custom RefinementList.
  • currentRefinement: currently applied refinement value (usually the call value of refine()).
  • createURL(value|item.value): will return a full url you can display for the specific refine value given you are using the routing feature.

The menu connector exposes a couple of properties more:

  • isShowingMore: equals true if the menu is displaying all the menu items
  • toggleShowMore: toggles the number of values displayed between limit and showMoreLimit
  • canToggleShowMore: equals true if the toggleShowMore button can be activated

If you compile your Angular application with AOT you will need to define the typings of the state class property. In this example it will look like this:

1
2
3
4
5
6
7
8
9
state: {
  items: { label: string; value: string }[];
  createURL: () => string;
  refine: (value: string) => void;
  canRefine: boolean;
  isShowingMore: boolean;
  toggleShowMore: () => void;
  canToggleShowMore: boolean;
}

4. Write the template

Last step, let’s write together the component template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Component, Inject, forwardRef, OnInit } from '@angular/core';
import { BaseWidget, NgAisInstantSearch } from 'angular-instantsearch';
import { connectMenu } from 'instantsearch.js/es/connectors';

@Component({
  selector: 'ais-menu-select',
  template: `
    <select
      class="menu-select"
      (change)="state.refine($event.target.value)"
    >
      <option
        *ngFor="let item of state.items"
        [value]="item.value"
        [selected]="item.isRefined"
      >
        {{item.label}}
      </option>
    </select>
  `
})
export class MenuSelect extends BaseWidget implements OnInit {
  state: {
    items: { label: string; value: string }[];
    createURL: () => string;
    refine: (value: string) => void;
    canRefine: boolean;
    isShowingMore: boolean;
    toggleShowMore: () => void;
    canToggleShowMore: boolean;
  }

  constructor(
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchParent
  ) {
    super('MenuSelect');
  }

  public ngOnInit() {
    this.createWidget(connectMenu, { attributeName: 'categories' });
    super.ngOnInit();
  }
}

Now you have a fully working example of a Menu widget rendered as a select HTML element.

Head over to our community forum if you still have questions about extending widgets.

Did you find this page helpful?