angularag-gridangular10

How to add Angular 10 Component to an Ag-Grid cell


I have an Angular10 component (toggle switch) that I need to include in a specific column of my ag-grid (cell).

At the moment I have a standard html checkbox as follows:

colDefs: ColDef[] = [
    { field: 'Name',             headerName: 'Name'},
    { field: 'Somethingelse',    headerName: 'Something else'},
    { field: 'Checkbox',         headerName: 'A Checkbox',      //<--this one
        editable:true,    
        checkboxSelection: false,   
        headerCheckboxSelection: false,   
        filter: false,    
        sortable: false,    
        cellRenderer: function (params: { value: boolean; }) {. //<--draws this
          var input = document.createElement("input");
          input.type = "checkbox";
          input.checked = params.value;
          return input;            //<--want to draw my component here instead
    } }
  ];

The component I would like to use instead of the checkbox already exists in my project:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'my-toggle-switch',
  templateUrl: './toggle-switch.component.html',
  styleUrls: ['./toggle-switch.component.scss']
})
export class ToggleSwitchComponent implements OnInit {
  selected: boolean = false;
  constructor() { }
  ngOnInit(): void {}
}

How do I include the Angular10 component in place of the checkbox?


Solution

  • first of all import your component in the AG Grid component file.

    import { ToggleSwitchComponent } from './ToggleSwitchComponent '; // whatever is the path
    

    2nd in coldef just assign your renderer to cellRenderer

      { 
            field: 'Checkbox',
            headerName: 'A Checkbox',
            editable:true,    
            checkboxSelection: false,   
            headerCheckboxSelection: false,   
            filter: false,    
            sortable: false,    
            cellRenderer: 'ToggleSwitchComponent'
        } }
    

    3rd register your component under frameworkComponents

     this.frameworkComponents = {
          ToggleSwitchComponent: ToggleSwitchComponent,
    ...
    ...
    }
    

    this is all your need to get your custom component to render.