🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / Angular InstantSearch / Widgets

Angular InstantSearch isn’t compatible with Angular’s Ivy view engine. We’re investigating how best to support this. For more information and to vote for Algolia’s support of Angular 16 and beyond, see the GitHub issue Algolia Support for Angular InstantSearch

Signature
<ais-hits
  // Optional parameters
  [transformItems]="function"
></ais-hits>
Import
1
2
3
4
5
6
7
8
import { NgAisHitsModule } from 'angular-instantsearch';

@NgModule({
  imports: [
    NgAisHitsModule,
  ],
})
export class AppModule {}

1. Follow additional steps in Optimize build size to ensure your code is correctly bundled.
2. This imports all the widgets, even the ones you don’t use. Read the Getting started guide for more information.

About this widget

Use ais-hits to display a list of results. To configure the number of hits to show, use one of:

For guidance on how to search across more than one index, read the multi-index search guide.

If there are no hits, you should display a message to users and clear filters so they can start over.

Examples

1
<ais-hits></ais-hits>

Properties

Parameter Description
transformItems
type: function
default: items => items
Optional

Receives the items and is called before displaying them. It returns a new array with the same shape as the original. This is helpful when transforming or reordering items. Don’t use transformItems to remove items since this will affect your pagination.

The entire results data is also available, including all regular response parameters and helper parameters (for example, disjunctiveFacetsRefinements).

If you’re transforming an attribute with the ais-highlight widget, you must transform item._highlightResult[attribute].value.

1
<ais-hits [transformItems]="transformItems"></ais-hits>

Templates

Parameter Description
hits
type: object[]

The matched hits from the Algolia API. You can use Algolia’s highlighting feature with the highlight component.

results
type: object

The complete response from the Algolia API. It contains the hits, metadata about the page, the number of hits, and so on. Unless you need to access metadata, use hits instead. You should also consider the stats widget if you want to build a widget that displays metadata about the search.

1
2
3
4
5
6
7
8
<ais-hits>
  <ng-template let-hits="hits" let-results="results">
    <div *ngFor="let hit of hits">
      Hit {{hit.objectID}}:
      <ais-highlight attribute="name" [hit]="hit"></ais-highlight>
    </div>
  </ng-template>
</ais-hits>
insights
type: function
signature: (method: string, payload: object) => void

Sends Insights events.

  • method: string: the Insights method to be called. Only search-related methods are supported: 'clickedObjectIDsAfterSearch', 'convertedObjectIDsAfterSearch'.
  • payload: object: the payload to be sent.
    • eventName: string: the name of the event.
    • objectIDs: string[]: a list of objectIDs.
    • index?: string: the name of the index related to the click.
    • queryID?: string: the Algolia queryID found in the search response when clickAnalytics: true.
    • userToken?: string: a user identifier.
    • positions?: number[]: the position of the click in the list of Algolia search results. When not provided, index, queryID, and positions are inferred by the InstantSearch context and the passed objectIDs:
    • index by default is the name of index that returned the passed objectIDs.
    • queryID by default is the ID of the query that returned the passed objectIDs.
    • positions by default is the absolute positions of the passed objectIDs. It’s worth noting that each element of items has the following read-only properties:
  • __queryID: the query ID (only if clickAnalytics is set to true).
  • __position: the absolute position of the item.

    For more details on the constraints of each payload property, refer to the Insights API client documentation.

1
2
3
4
5
6
7
8
9
10
11
12
13
<ais-hits>
  <ng-template let-hits="hits" let-insights="insights">
    <div *ngFor="let hit of hits">
      <ais-highlight attribute="name" [hit]="hit"></ais-highlight>
      <button (click)="insights(
        'clickedObjectIDsAfterSearch',
        { eventName: 'Add to cart', objectIDs: [hit.objectID] }
      )">
        Add to cart
      </button>
    </div>
  </ng-template>
</ais-hits>

HTML output

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="ais-Hits">
  <ul class="ais-Hits-list">
    <li class="ais-Hits-item">
      ...
    </li>
    <li class="ais-Hits-item">
      ...
    </li>
    <li class="ais-Hits-item">
      ...
    </li>
  </ul>
</div>

Customize the UI with connectHits

If you want to create your own UI of the ais-hits widget, you can combine the connectHits connector with the TypedBaseWidget class.

1. Extend the TypedBaseWidget class

First of all, you will need to write some boilerplate code to initialize correctly the TypedBaseWidget class. This happens in the constructor() of your class extending the TypedBaseWidget class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component, Inject, forwardRef, Optional } from '@angular/core';
import { TypedBaseWidget, NgAisInstantSearch, NgAisIndex } from 'angular-instantsearch';

@Component({
  selector: 'app-hits',
  template: '<p>It works!</p>'
})
export class Hits extends TypedBaseWidget {
  constructor(
    @Inject(forwardRef(() => NgAisIndex))
    @Optional()
    public parentIndex: NgAisIndex,
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchInstance: NgAisInstantSearch
  ) {
    super('Hits');
  }
}

There are a couple of things happening in this boilerplate:

  • create a Hits class extending TypedBaseWidget
  • reference the <ais-instantsearch> parent component instance on the Hits widget class
  • set app-hits as a selector, so we can use our component as <app-hits></app-hits>

2. Connect your custom widget

The TypedBaseWidget class has a method called createWidget() which takes two arguments: the connector to use and an object of options (instance options) for this connector. We call this method at ngOnInit. This component now implements OnInit.

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
import { Component, Inject, forwardRef, Optional } from '@angular/core';
import { TypedBaseWidget, NgAisInstantSearch, NgAisIndex } from 'angular-instantsearch';

import connectHits, {
  HitsWidgetDescription,
  HitsConnectorParams
} from 'instantsearch.js/es/connectors/hits/connectHits';

@Component({
  selector: 'app-hits',
  template: '<p>It works!</p>'
})
export class Hits extends TypedBaseWidget<HitsWidgetDescription, HitsConnectorParams> {
  public state: HitsWidgetDescription['renderState']; // Rendering options
  constructor(
    @Inject(forwardRef(() => NgAisIndex))
    @Optional()
    public parentIndex: NgAisIndex,
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchInstance: NgAisInstantSearch
  ) {
    super('Hits');
  }
  ngOnInit() {
    this.createWidget(connectHits, {
      // instance options
    });
    super.ngOnInit();
  }
}

3. Render from the state

Your component instance has access to a this.state property which holds the rendering options of the widget.

public state: HitsWidgetDescription['renderState'];
// {
//   hits: object[];
//   results: object;
//   sendEvent: (eventType, hit, eventName) => void;
// }
1
2
3
4
5
<ul>
  <li *ngFor="let hit of state.hits">
    <ais-highlight attribute="name" [hit]="hit"> </ais-highlight>
  </li>
</ul>

Rendering options

Parameter Description
hits
type: object[]

The matched hits from the Algolia API. You can use Algolia’s highlighting feature with the ais-highlight function, directly from the connector’s render function.

results
type: object

The complete response from the Algolia API. It contains the hits, metadata about the page, the number of hits, and so on. Unless you need to access metadata, use hits instead. You should also consider the stats widget if you want to build a widget that displays metadata about the search.

sendEvent
type: (eventType, hit, eventName) => void

The function to send click or conversion events. The view event is automatically sent when this connector renders hits.

  • eventType: 'click' | 'conversion'
  • hit: Hit | Hit[]
  • eventName: string

Learn more about these events in the insights middleware documentation.

Instance options

Parameter Description
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
customHits({
  escapeHTML: false,
});
transformItems
type: function
default: items => items
Optional

Receives the items and is called before displaying them. It returns a new array with the same “shape” as the original. This is helpful when transforming or reordering items. Don’t use transformItems to remove items since this will affect your pagination.

The entire results data is also available, including all regular response parameters and helper parameters (for example, disjunctiveFacetsRefinements).

If you’re transforming an attribute with the ais-highlight widget, you must transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
customHits({
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

/* or, combined with results */
customHits({
  transformItems(items, { results }) {
    return items.map((item, index) => ({
      ...item,
      position: { index, page: results.page },
    }));
  },
});

Full example

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
import { Component, Inject, forwardRef, Optional } from '@angular/core';
import { TypedBaseWidget, NgAisInstantSearch, NgAisIndex } from 'angular-instantsearch';

import connectHits, {
  HitsWidgetDescription,
  HitsConnectorParams
} from 'instantsearch.js/es/connectors/hits/connectHits';

@Component({
  selector: 'app-hits',
  template: `
<ul>
  <li *ngFor="let hit of state.hits">
    <ais-highlight attribute="name" [hit]="hit"> </ais-highlight>
  </li>
</ul>
`
})
export class Hits extends TypedBaseWidget<HitsWidgetDescription, HitsConnectorParams> {
  public state: HitsWidgetDescription['renderState']; // Rendering options
  constructor(
    @Inject(forwardRef(() => NgAisIndex))
    @Optional()
    public parentIndex: NgAisIndex,
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchInstance: NgAisInstantSearch
  ) {
    super('Hits');
  }
  ngOnInit() {
    this.createWidget(connectHits, {
      // instance options
    });
    super.ngOnInit();
  }
}

Click and conversion events

Did you find this page helpful?