Search code examples
angularvmware-clarity

How to get reference to clarity datagrid from typescript


This might be more of an angular question, but I'm trying to resize the clarity datagrid after loading data (and dynamically showing/hiding columns) but I keep getting the error

Uncaught TypeError: Cannot read property 'resize' of undefined

component.html

<clr-datagrid #contactsGrid>
[...]
</clr-datagrid>

component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Datagrid } from "clarity-angular";

export class GridComponent implements OnInit {
    @ViewChild('contactsGrid') datagrid: Datagrid;
    //@ViewChild('Datagrid') datagrid: Datagrid; //This doesn't work either

    constructor( ) { }

    ngOnInit() {
        [...]
        this.datagrid.resize(); //this.datagrid is undefined
    }
}

Solution

  • It appears your sample code above is correct, perhaps there is more going on? Do you have a more complete example to share that demonstrates the actual issue live?

    You can see a demo here of getting the reference for a datagrid. https://stackblitz.com/edit/clarity-datagrid-brfwx9?file=app/launches/launches.component.ts

    The template has:

    <clr-datagrid [(clrDgSelected)]="selected" #datagridRef>
    

    Then the controller has:

    export class LaunchesComponent  {
      @ViewChild('datagridRef') datagrid: Datagrid;
    
      ngOnInit() {
        console.log(this.datagrid); // Defined
      }
    

    If you only have one Datagrid, you don't need to add a hook in the HTML

    export class LaunchesComponent  {
      @ViewChild(Datagrid) datagrid: Datagrid;
    
      ngOnInit() {
        console.log(this.datagrid); // Defined
      }
    

    It looks like your code was passing 'Datagrid' (a string) instead of Datagrid(a reference to the constructor)