Hello fellow members of the Angular community,
I am seeking advice on how to create a generic icon component that avoids code duplication.
custom-icon-component:
@Component({
selector: 'app-custom-icon',
template: `
<style>
button {
background-color: Transparent;
border: none;
cursor: pointer;
overflow: hidden;
outline: none;
}
mat-icon {
font-size: 18px;
}
</style>
<button (click)="onClickCustomIcon($event)">
<mat-icon
matTooltip="Select action"
matTooltipPosition="below"
class="material-icons-outlined"
>{{ iconRegistry.CUSTOM }}</mat-icon
>
</button>
`,
styles: [],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomIconComponent implements ICellRendererAngularComp {
params;
disabled = false;
iconRegistry = IconRegistry;
agInit(params): void {
this.refresh(params);
}
refresh(params): boolean {
this.params = params;
return true;
}
onClickCustomIcon($event): void {
const params = {
rowData: this.params.data,
rowIndex: this.params.rowIndex
};
this.params.onClick(params);
}
update-icon-component:
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { IconRegistry } from '../../../icon-registry/icon-registry';
@Component({
selector: 'app-update-icon-render',
template: `
<style>
button {
background-color: Transparent;
border: none;
cursor: pointer;
overflow: hidden;
outline: none;
}
button :hover {
background-color: #efeadf;
}
mat-icon {
font-size: 18px;
}
</style>
<button
*ngIf="params?.data && !!params.data.objectId && !!params.data.objectPath"
(click)="onUpdateClick($event)"
[disabled]="params?.disabledGetter ? params.disabledGetter(params) : false"
data-cy="icon-cell-Update"
>
<mat-icon [matTooltip]="tooltip" matTooltipPosition="below" class="material-icons-outlined">
{{ iconRegistry.PENCIL }}
</mat-icon>
</button>
`,
styles: [],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UpdateIconRenderComponent implements ICellRendererAngularComp {
params;
iconRegistry = IconRegistry;
tooltip: string;
agInit(params): void {
this.params = params;
if (this.params?.tooltipGetter) {
this.tooltip = this.params.tooltipGetter(this.params);
} else {
this.tooltip = this.params?.tooltip;
}
}
onUpdateClick($event): void {
$event.stopPropagation();
const params = {
rowData: this.params.node.data
};
this.params.onClick(params);
}
refresh(params): boolean {
this.params = params;
return true;
}
The only variations are the ICON and logic within the agInit
function.
I cannot utilize the @Input feature since these components will be used within TypeScript code rather than HTML as shown below:
this.frameworkComponents = {
customButtonRenderer: CustomIconComponent
};
Any suggestions on creating a single generic component that can accommodate any icon?