【问题标题】:Angular Mat-Select - openedChange returns undefinedAngular Mat-Select - opensChange 返回未定义
【发布时间】:2020-05-26 22:52:29
【问题描述】:

当用户打开 mat-select 时,我正在使用自定义代码设置 css 样式。但它返回未定义的错误。 在控制台中,当我打印和检查元素值时,可以看到面板:未定义。 有人可以告诉我如何获得面板值。

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')
     }
}

【问题讨论】:

  • @angular/material 上的版本是什么?
  • @Eliseo - 版本 7。“@angular/material”:“^7.2.3”,
  • 对不起,我认为这可能是版本的问题,但是,在这个stackblitz.com/edit/angular-e5grmg?file=package.json 我无法重现该问题。您还有另一个元素,其中有一个名为#select 的“模板引用变量”? (请参阅我选择使用 select 但您可以使用 #myinput 并作为参数传递 (openedChange)="changeHeight($event,myinput)"
  • @Eliseo,您能否告诉我是否可以对多个 mat-select 使用相同的逻辑。目前我对多个 mat-select 使用相同的代码。这可能是出错的原因。
  • 如果 mat-select 在 *ngFor 中,没有混淆,否则你需要给每个不同的“模板引用变量”,例如使用#select1、#select2、#select3.. 和 (openedChange)="changeHeight($event,select1)", (openedChange)="changeHeight($event,select2)", (openedChange)="changeHeight($event, select3)"..顺便说一句,为什么不使用我在stackoverflow.com/questions/62016741/…答案的第二部分中指出的指令?

标签: html css angular angular-material


【解决方案1】:

添加这个

import { ViewChild } from "@angular/core";
import { MatSelect } from "@angular/material/select";

这是你的组件:

@ViewChild('select') select: MatSelect;

之后,如果需要,您可以将select 作为参数传递,或者直接删除参数并直接调用。

【讨论】:

    【解决方案2】:

    为构造函数的元素顶部设置元素引用,然后在模板#name 中设置与元素引用名称相同的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 2019-05-10
      • 1970-01-01
      • 2019-10-19
      • 2017-01-08
      • 2018-07-21
      • 2019-07-28
      • 2017-10-31
      相关资源
      最近更新 更多