【问题标题】:Inject host component in directive (material)在指令(材料)中注入宿主组件
【发布时间】:2018-11-09 08:59:23
【问题描述】:

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

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)])

提前致谢。

堆栈闪电战:https://stackblitz.com/edit/material-tooltip-select-search?file=src%2Fapp%2Fapp.component.html

【问题讨论】:

    标签: angular angular-material2


    【解决方案1】:

    要访问垫子上的所有属性,请选择您需要执行的操作 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...
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用ElementRef 访问它。

      在您的指令中注入 ElementRef 作为依赖项:

      import { ..., ElementRef, ... } from '@angular/core';
      ...
      constructor(private el: ElementRef) {}
      

      您现在可以在指令中使用 this.el 来访问 MatSelect。

      【讨论】:

      • @Leix,你能在这个答案之后解决你的问题吗?
      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      相关资源
      最近更新 更多