Skip to main content Skip to footer

Inserting a Custom SVG Icon into ComboBox in Angular

Background:

In some Angular applications, developers may want to customize the appearance of a ComboBox by displaying an SVG icon in front of the selected value in the input field, not just in the dropdown list. While Wijmo's ComboBox does not natively support input icons, this behavior can be achieved using native DOM access in combination with Angular lifecycle hooks.

Steps to Complete:

  1. Add an #inputGroup template reference to locate the ComboBox input
  2. Use ngAfterViewInit to insert the icon after the view is initialized
  3. Update the icon in response to value changes using the selectedIndexChanged event
  4. Add styling to position the icon properly

Getting Started:

Add template reference to the ComboBox container

In your Angular component’s template, add a wrapper around the ComboBox and give it a template reference:

<div class="wj-input-group" #inputGroup>
  <wj-combo-box
    [itemsSource]="items"
    displayMemberPath="name"
    (selectedIndexChanged)="onSelectionChange()"
    style="width: 250px;">
  </wj-combo-box>
</div>

 

Insert the icon using native DOM in ngAfterViewInit

In the component class, use @ViewChild to access the container and insert the icon after the view is initialized:

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-combo-icon',
  templateUrl: './combo-icon.component.html',
  styleUrls: ['./combo-icon.component.css']
})
export class ComboIconComponent implements AfterViewInit {
  @ViewChild('inputGroup', { static: false }) inputGroupRef!: ElementRef;
  icon1: string = '<svg width="16" height="16" ...>...</svg>'; // your SVG markup
  items = [{ name: 'Option 1' }, { name: 'Option 2' }];

  ngAfterViewInit(): void {
    this.insertIcon();
  }

  onSelectionChange(): void {
    if (!this.inputGroupRef.nativeElement.querySelector('.input-icon')) {
      this.insertIcon();
    }
  }

  private insertIcon(): void {
    const inputGroup = this.inputGroupRef.nativeElement;
    const iconSpan = document.createElement('span');
    iconSpan.className = 'input-icon';
    iconSpan.innerHTML = this.icon1;
    inputGroup.insertBefore(iconSpan, inputGroup.firstChild);
  }
}

 

Style the icon with CSS

In your component's CSS file, add styles to position the icon inside the input group:

.wj-input-group {
  position: relative;
}

.input-icon {
  position: absolute;
  top: 50%;
  left: 8px;
  transform: translateY(-50%);
  pointer-events: none;
}

You may also want to add left padding to the ComboBox input so that the text doesn’t overlap the icon.

This solution works well in Angular and provides full control over the SVG icon's appearance and placement in the input area of a ComboBox.

Hope you found this article helpful. Happy coding!

Andrew Peterson

Technical Engagement Engineer