如何访问角材料组件的属性?

seh*_*ler 6 material-design angular-material angular angular5

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

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

Yer*_*kon 8

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

  <mat-select #matSelect = 'matSelect'>
  ...
Run Code Online (Sandbox Code Playgroud)

组件.ts:

   @ViewChild('matSelect') child: MatSelect; 
   //or
   @ViewChild(MatSelect) child: MatSelect; 
Run Code Online (Sandbox Code Playgroud)

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

演示示例


Tom*_*ula 5

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

选择.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>
Run Code Online (Sandbox Code Playgroud)

选择.概述.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)
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示