How to access host component from directive?

前端 未结 6 459
北荒
北荒 2020-12-08 01:56

Say I have the following markup:


Is there any way I can access the component instance

6条回答
  •  再見小時候
    2020-12-08 02:50

    This is taken from the github issue and works like a charm. The downside is needing to know the components beforehand, but in your case you would need to know the methods you're using anyway.

    import { Host, Self, Optional } from '@angular/core';
    
        constructor(
             @Host() @Self() @Optional() public hostCheckboxComponent : MdlCheckboxComponent
            ,@Host() @Self() @Optional() public hostSliderComponent   : MdlSliderComponent){
                    if(this.hostCheckboxComponent) {
                           console.log("host is a checkbox");
                    } else if(this.hostSliderComponent) {
                           console.log("host is a slider");
                    }
             }
    

    Credit: https://github.com/angular/angular/issues/8277#issuecomment-323678013

提交回复
热议问题