bensalerno
bensalerno

Reputation: 534

Creating a searchbar for mat-cards in Angular?

My angular project is essentially a bunch of mat-cards that hold some buttons and images. When the button is clicked it directs you to another website. Pretty basic. The code is like this:

<mat-card id="CARDBOX" *ngFor="let box of box">
                      <img class="logoy" src="{{box.image}}" alt="Tesla" height=35px>
                      <a href="{{box.link}}" class="button">{{box.button_name}}</a>
                      <input type="image" id="info" title="Click for description" src="{{box.info}}" height=20px/>
</mat-card>

It looks like this Example

I would like to add a search bar at the top of the page so that one can search for a certain link and access it from the autocomplete dropdown that would accompany the search bar. I.e. if one types "Example" then the autocomplete would give Example1, Example2, Example3, and you could click on that and it would link you to the appropriate website the same way that clicking the button on the mat-card would. Is there some kind of library that makes this easy? Or do I have to implement it in the backend? Is this possible to do in Angular? I haven't been able to find any documentation on the matter. If so, how should I go about implementing this into my project?

Upvotes: 0

Views: 2047

Answers (1)

Hansaka Sandaruwan
Hansaka Sandaruwan

Reputation: 521

Use angular material Autocomplete.

Following will be your search bar.

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

this will be your typescript code.

 myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }

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

    return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
  }

full example from angular material stackblitz

_filter function without showing result at first

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
   if(filterValue == ''){
      return []
    }
    return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
  }

Upvotes: 1

Related Questions