0

I am trying to implement an angular material select component in the AG-GRID as per the example described here

However when I click on the cell that should make the select appear, it does not appear and in the console the following error appears:

core.js:4002 ERROR TypeError: Cannot read property 'element' of undefined
at mat-select.component.ts:37

This corresponds to the following method in the MatSelectComponent:

// dont use afterGuiAttached for post gui events - hook into ngAfterViewInit instead for this
ngAfterViewInit() {
    window.setTimeout(() => {
        this.group.element.nativeElement.focus();
    });
    this.selectFavouriteVegetableBasedOnSelectedIndex();
}

This component has been copied exactly from the example given, except that I put the template and styles in their own HTML/SCSS files respectively.

@Component({
  selector: 'radio-cell',
  template: './mat-select.component.html'
  styles: ['./mat-slect.component.scss']
})

However, when I include the HTML template within the component like in the example it works!

@Component({
  selector: 'radio-cell',
  template: `
  <mat-card>
    <div class="container" #group tabindex="0" (keydown)="onKeyDown($event)">
      <mat-form-field>
        <mat-select panelClass="ag-custom-component-popup" [(ngModel)]="favouriteVegetable">
          <mat-option *ngFor="let vegetable of vegetables" [value]="vegetable">
            {{ vegetable }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
  </mat-card>
  `,
  styles: ['./mat-slect.component.scss']
})

Is there any explaination of this behaviour or way around putting all this HTML into the component?

EDIT 1: The component includes the 'group' template reference variable in the component like below, so should it not be available to the ngAfterViewInit() method?

    @ViewChild("group", { read: ViewContainerRef, static: true })
    public group;
Tom O'Brien
  • 1,741
  • 9
  • 45
  • 73

1 Answers1

0

Your error Cannot read property 'element' of undefined comes from the fact that this.group is undefined because angular tries to query it in the template but doesn't find it <div class="container"#grouptabindex="0" (keydown)="onKeyDown($event)">

Rachid O
  • 13,013
  • 15
  • 66
  • 92
  • But in the component it has: @ViewChild("group", { read: ViewContainerRef, static: true }) public group; Does this not mean it should be available in the component too? – Tom O'Brien May 28 '20 at 16:47
  • no it does not mean that `group` will be available, `group` will stay `undefined` until it is found in the template – Rachid O May 28 '20 at 16:52
  • Why would it not be found inside the ngViewAfterInit()? According to this it should be able to be used: https://stackoverflow.com/questions/39631594/access-template-reference-variables-from-component-class – Tom O'Brien May 28 '20 at 16:56