Skip to content

Instantly share code, notes, and snippets.

@MithrilMan
Last active December 8, 2019 12:52
Show Gist options
  • Select an option

  • Save MithrilMan/46de5430df3f5945f68e3e1e64d46a18 to your computer and use it in GitHub Desktop.

Select an option

Save MithrilMan/46de5430df3f5945f68e3e1e64d46a18 to your computer and use it in GitHub Desktop.
Angular component that mimic mat-chip aspect without requiring mat-chiplist

Angular component that mimic mat-chip aspect without requiring mat-chiplist It's based on angular material styles and it just adds a bounch of already existent classes in order to have the chip aspect without requiring you to add lot of boilerplate code to have a simple chip (like manually having to include a mat-chip-list or a selected to have colors.

It's not meant to be used as a replacement for chip because it has no events and it's not clickable. It's meant to be an implementation closer to bootstrap badges

<chip color="primary">My Primary Chip</chip>
<chip color="accent">My Accent Chip</chip>
<chip color="warn">My Warn Chip</chip>

P.S.

  • remember to add the component into the declarations section of the module that need to use the component...
  • actually to have a proper render, you need anyway to include a somewhere on your page, I add it automatically injecting one if the page doesn't have the "fix" (display=none so doesn't impact layout)
import { Component, OnInit, Input, AfterViewInit, ViewChild, ViewContainerRef, TemplateRef } from '@angular/core';
@Component({
selector: 'chip',
template: `
<ng-template #fixTemplate>
<!--ugly fix for chips, add an hidden mat-chip-list to be able to add mat-chip without including them in the list-->
<mat-chip-list style="display:none" id="chip-fix" disabled></mat-chip-list>
</ng-template>
<ng-container #fixContainer></ng-container>
<ng-content></ng-content>
`,
host: {
class: 'mat-chip mat-chip-selected mat-standard-chip ',
'[class.mat-accent]': 'color=="accent"',
'[class.mat-primary]': 'color=="primary"',
'[class.mat-warn]': 'color=="warn"'
}
})
export class ChipComponent implements OnInit {
@Input() color: string;
@ViewChild('fixContainer', { read: ViewContainerRef, static: true })
chipFix: ViewContainerRef;
@ViewChild('fixTemplate', { read: TemplateRef, static: true })
fixTemplate: TemplateRef<null>;
ngOnInit(): void {
if (!document.getElementById("chip-fix")) {
this.chipFix.createEmbeddedView(this.fixTemplate);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment