如何获取角材料组件的属性?

时间:2018-04-12 09:56:40

标签: angular material-design angular-material angular5

我对角度很新,我用它构建了我的前几个应用程序,现在我正在开发一个包含角度材料的项目。

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

2 个答案:

答案 0 :(得分:3)

注意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

答案 1 :(得分:0)

您可以使用@ViewChild装饰器。查询从MatSelect导入的@angular/material组件。请记住,@ViewChild装饰器查询的元素在视图为init之后可用(因此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