Is there any way to add href link for mat-chips component as property or attribute

Viewed 89

I am trying to add a new icon and possibly a href on the mat-chip component but I want it as properties and not to hardcode into that. So the idea is to have it as a component so I can call it from another component and give data. For example links, and icons are on the left side and right sides. Icons on left should be an edit icon and the right will be default remove. But at the hovering, both of them need to be highlighted. So let's say if from another component we define the left icon then it will be shown and if not then will be not shown. Or can it be done within a directive too?

I have till now created like this but I think I need more to do on that. See stackblitz. Maybe instead of ngIf is any other way to use it. But I want for example that in the child component to send the index so then I can use it into href. But in the child, I cannot use the index so I can iterate through the components and use the href for each of them and I want to use this component for different data. see components in stack blitz. users and group components. 1 of them has a variable name and the other one has a username.

https://stackblitz.com/edit/angular-3vp4xw-a9jeot?file=src/app/chips-autocomplete-example.ts

2 Answers

What about somethin like that :

You create a component like 'mat-chip-link':

<mat-chip *ngFor="let fruit of fruits" (removed)="remove(fruit)">

  <ng-content select="[.beforeLink]"></ng-content>

  <a
    [href]="link"
    class="mat-standard-chip"
    target="_blank"
    style="margin: 0; padding: 0"
    >My link</a
  >
  
  <ng-content select="[.afterLink]"></ng-content>
</mat-chip>

(I am not sure about the ng-content selector, check the doc here for more info. https://angular.io/guide/content-projection). Which has an input like @Input link: string;

Then from the parent you can call this component like that

    <mat-chip-link *ngFor="let fruit of fruits" (removed)="remove(fruit)" [link]="test"> 
  <mat-icon matChipRemove class="beforeLink" *ngIf="editable">cancel</mat-icon>
  <mat-icon matChipRemove class="afterLink" *ngIf="removable">cancel</mat-icon>
</mat-chip>

It might be done easier, for example (Typescript):

Template of custom component mat-chip-link

<mat-chip-link (click)="this.clickEventHandler($event)"/>
  <mat-chip>
    <ng-content>
    </ng-content>
  </mat-chip>
</mat-chip-link>

Component

private _href: string | null = null;

@Input('href') public set href(value: string | null) {
  this._href = value;
}

public clickEventHandler(e: MouseEvent) {
  if(this._href !== null) {
    window.open(this._href, '_blank');
  } else {
    console.log('No href specifief');
  }
}

Usage

<mat-chip-link [href]="https://www.stackoverflow.com">
  Jump to StackOverflow 
</mat-chip-link>
Related