Add this
import { ViewChild } from "@angular/core";
import { MatSelect } from "@angular/material/select";
and this to your component:
@ViewChild('select') select: MatSelect;
Afterwards you can, if you need it, pass select
as a parameter or just remove the parameter and call it directly.
set elementref for element top of constructor then set the same name in your template #name with your elementref name.
I am setting css style using custom code when user opens mat-select. But it returns undefined error.
In console, when I print and check element values, could see panel:undefined.
Can someone please let me know How to get the panel value.
Error: Cannot read property 'nativeElement' of undefined
Html:
<mat-select #select (openedChange)="changeHeight($event,select)">
<mat-option>1</mat-option>
<mat-option>2</mat-option>
</mat-select>
component.ts:
import { Component, OnInit, Inject, Renderer2, ElementRef } from '@angular/core';
constructor(private renderer:Renderer2){}
changeHeight(event:any,element:any)
{
if (event)
{
const height = window.innerHeight||
document.documentElement.clientHeight||
document.body.clientHeight;
this.renderer.setStyle(element.panel.nativeElement,
'max-height',
(height-10-element.panel.nativeElement.getBoundingClientRect().y)+'px')
}
}
@Eliseo – Version 7. “@angular/material”: “^7.2.3”,
@Eliseo, Could you please tell me if I can use same logic for multiple mat-select. Currently I am using same code for multiple mat-select. This could be the possible reason for error.
if the mat-select are in a *ngFor, there’re NO confussion, else you need give differents “template reference variable” to each one, e.g. use #select1, #select2,#select3.. and (openedChange)=”changeHeight($event,select1)”, (openedChange)=”changeHeight($event,select2)”, (openedChange)=”changeHeight($event,select3)”.. BTW, why not use a directive as I indicate in the second part of the answer in