How to access properties of angular material components?

回眸只為那壹抹淺笑 提交于 2021-02-20 10:12:23

问题


I'm fairly new to angular in general, i have built my first few apps with it and right now I'm working on some project that contains angular material.

When i go to this site i see lots of properties of the MatSelect directive. There is one property called 'empty: boolean' that I would like to access in some way, but i don't know how, can you help me?


回答1:


Pay attention to Exported as:matSelect. You can reference it by template reference variable(#var) or by 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




回答2:


You can use the @ViewChild decorator. Query for the MatSelect component imported from @angular/material. Keep in mind that elements queried by the @ViewChild decorator are available after the view is init (hence the ngAfterViewInit lifecycle hook).

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



来源:https://stackoverflow.com/questions/49793554/how-to-access-properties-of-angular-material-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!