Home > Software design >  How to keep the leading and trailing spaces in mat-chip?
How to keep the leading and trailing spaces in mat-chip?

Time:07-29

HTML

<mat-form-field >
  <mat-chip-list #chipList aria-label="Fruit selection">
    <mat-chip
      *ngFor="let fruit of fruits"
      [selectable]="selectable"
      [removable]="removable"
      (removed)="remove(fruit)">
      {{fruit}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input
      placeholder="New fruit..."
      #fruitInput
      [formControl]="fruitCtrl"
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      [matChipInputAddOnBlur]="addOnBlur"
      (matChipInputTokenEnd)="add($event)">
  </mat-chip-list>
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
    <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
      {{fruit}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

COMPONENT TS

import {Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete, MatAutocompleteTrigger} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import {Observable, fromEvent} from 'rxjs';
import {map, startWith, tap} from 'rxjs/operators';
/**
 * @title Chips Autocomplete
 */
@Component({
  selector: 'chips-autocomplete-example',
  templateUrl: 'chips-autocomplete-example.html',
  styleUrls: ['chips-autocomplete-example.css'],
})
export class ChipsAutocompleteExample implements AfterViewInit {
  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  fruitCtrl = new FormControl();
  filteredFruits: Observable<string[]>;
  fruits: string[] = ['Lemon'];
  allFruits: string[] = ['Apple ', ' Lemon', 'Lime', 'Orange', 'Strawberry'];

  @ViewChild('fruitInput', {static: false}) fruitInput: ElementRef<HTMLInputElement>;
  @ViewChild('auto', {static: false}) matAutocomplete: MatAutocomplete;
  @ViewChild(MatAutocompleteTrigger, {static: false}) trigger: MatAutocompleteTrigger;

  constructor() {
    this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
        startWith(null),
        map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
        console.log(this.allFruits)
  }

  ngAfterViewInit() {
    fromEvent(this.fruitInput.nativeElement, 'click')
      .pipe(
        tap(() => {
          this.trigger.openPanel()
        })
      ).subscribe()
  }


  add(event: MatChipInputEvent): void {
    // Add fruit only when MatAutocomplete is not open
    // To make sure this does not conflict with OptionSelected Event
    if (!this.matAutocomplete.isOpen) {
      const input = event.input;
      const value = event.value;

      // Add our fruit
      if (value) {
        this.fruits.push(value);
      }

      // Reset the input value
      if (input) {
        input.value = '';
      }

      this.fruitCtrl.setValue(null);
    }
  }

  remove(fruit: string): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
    console.log(this.fruits)
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
  }
}

I have list of fruits, with the help mat-autocomplete i can select the particular value, selected value convert into a mat-chip.

problem is initially fruit ' Lemon' have whitespace before L and 'Apple ' have whitespace after e, you can clearly see in the console initially array values have the whitespaces, after convert into an mat-chip in the console the whitespaces are automatically got removed, but i want those whitespaces in my mat-chip, how to do that ?

Stackblitz here https://stackblitz.com/edit/angular-sb38ig-fphy7s?file=app/chips-autocomplete-example.ts,app/chips-autocomplete-example.html

CodePudding user response:

In your styles.css:

mat-chip.mat-chip{white-space: pre;}

component.ts use value and not viewValue:

selected(event: MatAutocompleteSelectedEvent): void {
  // this.fruits.push(event.option.viewValue);
  this.fruits.push(event.option.value);

Then add any white spaces to your chips at beginning or end, it should work.

  • Related