File

src/search/search.component.ts

Description

Get started with importing the module:

Example :
import { SearchModule } from 'carbon-components-angular';

See demo

Implements

ControlValueAccessor

Metadata

Index

Properties
Methods
Inputs
Outputs
HostBindings
HostListeners
Accessors

Constructor

constructor(elementRef: ElementRef, i18n: I18n)

Creates an instance of Search.

Parameters :
Name Type Optional Description
elementRef ElementRef No
i18n I18n No

The i18n translations.

Inputs

active
Type : boolean
Default value : false

Set to true to expand the toolbar search component.

ariaLabel
Type : string

Sets the aria label on the div element with the search role.

autocomplete
Type : string
Default value : "on"

Sets the autocomplete attribute on the input element. For reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#Values

clearButtonTitle
Type : any
Default value : this.i18n.get().SEARCH.CLEAR_BUTTON

Used to set the title attribute of the clear button.

disabled
Type : boolean
Default value : false

Set to true for a disabled search input.

expandable
Type : boolean
Default value : false

Set to true to make the search component expandable. expandable would override toolbar property behaviours.

fluid
Type : boolean
Default value : false

Experimental: enable fluid state

id
Type : string
Default value : `search-${Search.searchCount}`

The unique id for the search component.

label
Type : any
Default value : this.i18n.get().SEARCH.LABEL

Sets the text inside the label tag.

name
Type : string

Sets the name attribute on the input element.

placeholder
Type : any
Default value : this.i18n.get().SEARCH.PLACEHOLDER

Sets the placeholder attribute on the input element.

required
Type : boolean

Reflects the required attribute of the input element.

searchTitle
Type : string
Default value : ""

Title for the search trigger

size
Type : "sm" | "md" | "lg"
Default value : "md"

Size of the search field.

skeleton
Type : boolean
Default value : false

Set to true for a loading search component.

tableSearch
Type : boolean
Default value : false

Specifies whether the search component is used in the table toolbar.

theme
Type : "light" | "dark"
Default value : "dark"
toolbar
Type : boolean
Default value : false

Set to true for a toolbar search component.

value
Type : string
Default value : ""

Sets the value attribute on the input element.

Outputs

clear
Type : EventEmitter

Emits an event when the clear button is clicked.

open
Type : EventEmitter
search
Type : EventEmitter

Emits an event on enter.

valueChange
Type : EventEmitter

Emits an event when value is changed.

HostBindings

class.cds--form-item
Type : boolean
class.cds--text-input--fluid__skeleton
Type : boolean

HostListeners

compositionend
Arguments : '$event'
compositionend(event)

Called when IME composition finishes.

compositionstart
Arguments : '$event'
compositionstart(event)

Called when using IME composition.

focusin
Arguments : '$event'
focusin(event)
focusout
Arguments : '$event'
focusout(event)
keydown
Arguments : '$event'
keydown(event: KeyboardEvent)

Methods

clearSearch
clearSearch()

Called when clear button is clicked.

Returns : void
compositionEnd
compositionEnd(event)
Decorators :
@HostListener('compositionend', ['$event'])

Called when IME composition finishes.

Parameters :
Name Optional
event No
Returns : void
compositionStart
compositionStart(event)
Decorators :
@HostListener('compositionstart', ['$event'])

Called when using IME composition.

Parameters :
Name Optional
event No
Returns : void
doValueChange
doValueChange()
Returns : void
focusIn
focusIn(event)
Decorators :
@HostListener('focusin', ['$event'])
Parameters :
Name Optional
event No
Returns : void
focusOut
focusOut(event)
Decorators :
@HostListener('focusout', ['$event'])
Parameters :
Name Optional
event No
Returns : void
keyDown
keyDown(event: KeyboardEvent)
Decorators :
@HostListener('keydown', ['$event'])
Parameters :
Name Type Optional
event KeyboardEvent No
Returns : void
onEnter
onEnter()

Called on enter.

Returns : void
onSearch
onSearch(search: string)

Called when text is written in the input.

Parameters :
Name Type Optional Description
search string No

The input text.

Returns : void
openSearch
openSearch()
Returns : void
Public registerOnChange
registerOnChange(fn: any)

Sets a method in order to propagate changes back to the form.

Parameters :
Name Type Optional
fn any No
Returns : void
Public registerOnTouched
registerOnTouched(fn: any)

Registers a callback to be triggered when the control has been touched.

Parameters :
Name Type Optional Description
fn any No

Callback to be triggered when the search input is touched.

Returns : void
Public writeValue
writeValue(value: any)

This is the initial value set to the component

Parameters :
Name Type Optional Description
value any No

The input value.

Returns : void

Properties

inputRef
Type : ElementRef
Decorators :
@ViewChild('input')
Protected isComposing
Default value : false

Sets true when composing text via IME.

onTouched
Type : function
Default value : () => {...}

Called when search input is blurred. Needed to properly implement ControlValueAccessor.

propagateChange
Default value : () => {...}

Method set in registerOnChange to propagate changes back to the form.

Static searchCount
Type : number
Default value : 0

Variable used for creating unique ids for search components.

Accessors

containerClass
getcontainerClass()
fluidSkeletonClass
getfluidSkeletonClass()
import {
	Component,
	Input,
	EventEmitter,
	Output,
	HostBinding,
	ElementRef,
	HostListener,
	ViewChild
} from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";
import { I18n } from "carbon-components-angular/i18n";

/**
 * Get started with importing the module:
 *
 * ```typescript
 * import { SearchModule } from 'carbon-components-angular';
 * ```
 *
 * [See demo](../../?path=/story/components-search--basic)
 */
@Component({
	selector: "cds-search, ibm-search",
	templateUrl: "search.component.html",
	providers: [
		{
			provide: NG_VALUE_ACCESSOR,
			useExisting: Search,
			multi: true
		}
	]
})
export class Search implements ControlValueAccessor {
	/**
	 * Variable used for creating unique ids for search components.
	 */
	static searchCount = 0;

	@HostBinding("class.cds--form-item") get containerClass() {
		return !(this.toolbar || this.expandable);
	}

	@HostBinding("class.cds--text-input--fluid__skeleton") get fluidSkeletonClass() {
		return this.skeleton && this.fluid;
	}

	/**
	 * @deprecated since v5 - Use `cdsLayer` directive instead
	 * `light` or `dark` search theme.
	 */
	@Input() theme: "light" | "dark" = "dark";

	/**
	 * Size of the search field.
	 */
	@Input() size: "sm" | "md" | "lg" = "md";

	/**
	 * Set to `true` for a disabled search input.
	 */
	@Input() disabled = false;
	/**
	 * Set to `true` for a toolbar search component.
	 */
	@Input() toolbar = false;
	/**
	 * Set to `true` to make the search component expandable.
	 * `expandable` would override `toolbar` property behaviours.
	 */
	@Input() expandable = false;
	/**
	 * Set to `true` for a loading search component.
	 */
	@Input() skeleton = false;
	/**
	 * Set to `true` to expand the toolbar search component.
	 */
	@Input() active = false;
	/**
	 * Specifies whether the search component is used in the table toolbar.
	 */
	@Input() tableSearch = false;
	/**
	 * Sets the name attribute on the `input` element.
	 */
	@Input() name: string;
	/**
	 * The unique id for the search component.
	 */
	@Input() id = `search-${Search.searchCount}`;
	/**
	 * Reflects the required attribute of the `input` element.
	 */
	@Input() required: boolean;
	/**
	 * Sets the value attribute on the `input` element.
	 */
	@Input() value = "";
	/**
	 * Sets the autocomplete attribute on the `input` element.
	 * For reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#Values
	 */
	@Input() autocomplete = "on";
	/**
	 * Sets the text inside the `label` tag.
	 */
	@Input() label = this.i18n.get().SEARCH.LABEL;
	/**
	 * Sets the placeholder attribute on the `input` element.
	 */
	@Input() placeholder = this.i18n.get().SEARCH.PLACEHOLDER;
	/**
	 * Used to set the `title` attribute of the clear button.
	 */
	@Input() clearButtonTitle = this.i18n.get().SEARCH.CLEAR_BUTTON;
	/**
	 * Title for the search trigger
	 */
	@Input() searchTitle = "";
	/**
	 * Sets the aria label on the `div` element with the `search` role.
	 */
	@Input() ariaLabel: string;
	/**
	 * Experimental: enable fluid state
	 */
	@Input() fluid = false;
	/**
	 * Emits an event when value is changed.
	 */
	@Output() valueChange = new EventEmitter<string>();
	@Output() open = new EventEmitter<boolean>();
	/**
	 * Emits an event when the clear button is clicked.
	 */
	@Output() clear = new EventEmitter();
	/**
	 * Emits an event on enter.
	 */
	@Output() search = new EventEmitter<string>();

	@ViewChild("input") inputRef: ElementRef;

	/**
	 * Sets `true` when composing text via IME.
	 */
	protected isComposing = false;

	/**
	 * Creates an instance of `Search`.
	 * @param i18n The i18n translations.
	 */
	constructor(protected elementRef: ElementRef, protected i18n: I18n) {
		Search.searchCount++;
	}

	/**
	 * This is the initial value set to the component
	 * @param value The input value.
	 */
	public writeValue(value: any) {
		this.value = value;
	}

	/**
	 * Sets a method in order to propagate changes back to the form.
	 */
	public registerOnChange(fn: any) {
		this.propagateChange = fn;
	}

	/**
	 * Registers a callback to be triggered when the control has been touched.
	 * @param fn Callback to be triggered when the search input is touched.
	 */
	public registerOnTouched(fn: any) {
		this.onTouched = fn;
	}

	/**
	 * Called when search input is blurred. Needed to properly implement `ControlValueAccessor`.
	 */
	onTouched: () => any = () => {};

	/**
	 * Method set in `registerOnChange` to propagate changes back to the form.
	 */
	propagateChange = (_: any) => {};

	/**
	 * Called when text is written in the input.
	 * @param search The input text.
	 */
	onSearch(search: string) {
		if (this.isComposing) { // check for IME use
			return;
		}
		this.value = search;
		this.doValueChange();
	}

	/**
	 * Called on enter.
	 */
	onEnter() {
		this.search.emit(this.value);
	}

	/**
	 * Called when clear button is clicked.
	 */
	clearSearch(): void {
		this.value = "";
		this.doValueChange();
		this.clear.emit();
	}

	doValueChange() {
		this.propagateChange(this.value);
		this.valueChange.emit(this.value);
	}

	openSearch() {
		this.active = true;
		this.open.emit(this.active);
		setTimeout(() => this.inputRef.nativeElement.focus());
	}

	@HostListener("keydown", ["$event"])
	keyDown(event: KeyboardEvent) {
		if (this.toolbar || this.expandable) {
			if (event.key === "Escape") {
				if (this.value === "") {
					this.active = false;
					this.open.emit(this.active);
				}
			} else if (event.key === "Enter") {
				this.openSearch();
			}
		}

		if (event.key === "Escape") {
			if (this.value !== "") {
				this.clearSearch();
			}
		}
	}

	@HostListener("focusout", ["$event"])
	focusOut(event) {
		this.onTouched();
		if ((this.expandable || this.toolbar) &&
			this.inputRef &&
			this.inputRef.nativeElement.value === "" &&
			!(this.elementRef.nativeElement as HTMLElement).contains(event.relatedTarget)) {
			this.active = false;
			this.open.emit(this.active);
		}
	}

	@HostListener("focusin", ["$event"])
	focusIn(event) {
		this.onTouched();
		// set input focus if search icon get focus from tab key press event.
		if ((this.expandable || this.toolbar) &&
			this.inputRef && !event.relatedTarget &&
			!(this.elementRef.nativeElement as HTMLElement).contains(event.relatedTarget) ) {
			this.openSearch();
		}
	}

	/**
	 * Called when using IME composition.
	 */
	@HostListener("compositionstart", ["$event"])
	compositionStart(event) {
		this.isComposing = true;
	}

	/**
	 * Called when IME composition finishes.
	 */
	@HostListener("compositionend", ["$event"])
	compositionEnd(event) {
		this.isComposing = false;
		this.onSearch(this.value + event.data);
	}
}
<div
	class="cds--search"
	[ngClass]="{
		'cds--search--sm': size === 'sm',
		'cds--search--md': size === 'md',
		'cds--search--lg': size === 'lg',
		'cds--search--light': theme === 'light',
		'cds--skeleton': skeleton && !fluid,
		'cds--search--expandable': expandable && !tableSearch,
		'cds--search--expanded': expandable && !tableSearch && active,
		'cds--toolbar-search': toolbar && !expandable,
		'cds--toolbar-search--active': toolbar && !expandable && active,
		'cds--toolbar-search-container-persistent': tableSearch && !expandable,
		'cds--toolbar-search-container-expandable': tableSearch && expandable,
		'cds--toolbar-search-container-active': tableSearch && expandable && active,
		'cds--search--fluid': fluid,
		'cds--search--disabled': disabled
	}"
	role="search"
	[attr.aria-label]="ariaLabel"
	(click)="openSearch()">
	<label
		class="cds--label"
		[for]="id"
		[ngClass]="{ 'cds--skeleton': skeleton && fluid }">
		{{ !skeleton ? label : ''}}
	</label>

	<div *ngIf="skeleton; else enableInput" class="cds--text-input cds--skeleton"></div>
	<ng-template #enableInput>
		<input
			#input
			class="cds--search-input"
			[type]="tableSearch || !toolbar ? 'text' : 'search'"
			[id]="id"
			[value]="value"
			[autocomplete]="autocomplete"
			[placeholder]="placeholder"
			[disabled]="disabled"
			[required]="required"
			(input)="onSearch($event.target.value)"
			(keyup.enter)="onEnter()"/>
		<button
			*ngIf="!tableSearch && toolbar"
			class="cds--toolbar-search__btn"
			(click)="openSearch()"
			aria-label="Open search">
			<svg cdsIcon="search" size="16" class="cds--search-magnifier-icon"></svg>
		</button>
		<svg
			cdsIcon="search"
			*ngIf="tableSearch || !toolbar"
			class="cds--search-magnifier-icon"
			size="16">
		</svg>
	</ng-template>

	<button
		*ngIf="tableSearch || !toolbar"
		class="cds--search-close"
		[ngClass]="{
			'cds--search-close--hidden': !value || value.length === 0
		}"
		[title]="clearButtonTitle"
		(click)="clearSearch()">
		<span class="cds--visually-hidden">{{ clearButtonTitle }}</span>
		<svg cdsIcon="close" size="16"></svg>
	</button>
</div>
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""