【问题标题】:How to access properties of angular material components?如何访问角材料组件的属性?
【发布时间】:2018-04-12 09:56:39
【问题描述】:

总的来说,我对 Angular 还很陌生,我已经用它构建了我的前几个应用程序,现在我正在处理一些包含 Angular 材料的项目。

当我访问this 站点时,我看到了 MatSelect 指令的许多属性。我想以某种方式访问​​一个名为“empty: boolean”的属性,但我不知道如何访问,您能帮帮我吗?

【问题讨论】:

    标签: angular material-design angular-material angular5


    【解决方案1】:

    关注Exported as:matSelect。您可以通过模板引用变量(#var) 或 ViewChild 来引用它:

      <mat-select #matSelect = 'matSelect'>
      ...
    

    component.ts:

       @ViewChild('matSelect') child: MatSelect; 
       //or
       @ViewChild(MatSelect) child: MatSelect; 
    

    https://material.angular.io/components/select/api#MatSelect

    Demo Example

    【讨论】:

    • #matSelect = 'matSelect' 可以替换为#matSelect
    • @trichetriche,是的,谢谢?,喜欢:&lt;mat-select #matSelect&gt; 这样更清楚
    【解决方案2】:

    您可以使用@ViewChild 装饰器。查询从@angular/material 导入的MatSelect 组件。请记住,@ViewChild 装饰器查询的元素在视图初始化后可用(因此有 ngAfterViewInit 生命周期挂钩)。

    select.overview.html

    <mat-form-field>
      <mat-select placeholder="Favorite food">
        <mat-option *ngFor="let food of foods" [value]="food.value">
          {{ food.viewValue }}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    select.overview.ts

    import {Component, ViewChild, AfterViewInit} from '@angular/core';
    import {MatSelect} from '@angular/material';
    
    @Component({
      selector: 'select-overview-example',
      templateUrl: 'select-overview-example.html',
      styleUrls: ['select-overview-example.css'],
    })
    export class SelectOverviewExample implements AfterViewInit{
      @ViewChild(MatSelect) select: MatSelect;
    
      foods = [
        {value: 'steak-0', viewValue: 'Steak'},
        {value: 'pizza-1', viewValue: 'Pizza'},
        {value: 'tacos-2', viewValue: 'Tacos'}
      ];
    
      ngAfterViewInit() {
        console.log(this.select.empty)
      }
    }
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 2019-01-07
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      相关资源
      最近更新 更多