首页 > 解决方案 > 在指令(材料)中注入宿主组件

问题描述

我可以像这样在指令构造函数中注入一个组件:

constructor(private hello: HelloComponent) {
  console.log(hello.test)
}

这项工作很好,但我的指令需要专门与 Mat-Select 一起工作,所以我正在尝试这样的事情:

constructor(private matSelect: MatSelect) {
  console.log(matSelect)
}

这种方式行不通:

Error: StaticInjectorError(AppModule)[SelectSearchDirective -> MatSelect]: 
StaticInjectorError(Platform: core)[SelectSearchDirective -> MatSelect]: 
NullInjectorError: No provider for MatSelect!

有没有办法访问 MatSelect (我需要玩 [(value)])

提前致谢。

Stackblitz:https ://stackblitz.com/edit/material-tooltip-select-search?file=src%2Fapp%2Fapp.component.html

标签: angularangular-material2

解决方案


要访问垫子上的所有属性,请选择您需要 import {MatSelect} from '@angular/material'; 在组件中执行的操作, @ViewChild('myTemplateReference') select: MatSelect;

在 html 上你只需要添加模板引用

 <mat-select #myTemplateReference [(ngModel)]="value">

有了这一切,该select属性现在为您提供了 mat select 的所有方法和属性。

但如果你只需要价值,为什么不直接使用[(ngModel)]="value"

然后在选择更改使用(selectionChange)="doSomething()"

doSomething(){

    this.value...
}

推荐阅读