How to access host component from directive?

前端 未结 6 461
北荒
北荒 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:46

    I do like this, it works on Angular 9.

    export class FromItemComponentBase  {
      constructor(private hostElement: ElementRef) {
        hostElement.nativeElement.__component=this;
      }
    }
    

    @Component({
      selector: 'input-error',
      templateUrl: 'component.html'
    })
    export class FromItemErrorComponent extends FromItemComponentBase {
      constructor(private hostElement: ElementRef) {
        super(hostElement);
      }
    }
    
    @Component({
      selector: 'input-password',
      templateUrl: 'component.html'
    })
    export class FromItemPasswordComponent extends FromItemComponentBase {
      constructor(private hostElement: ElementRef) {
        super(hostElement);
      }
    }
    

    @Directive({selector: 'input-error,input-password,input-text'})
    export class FormInputDirective {
      component:FromItemComponentBase;
    
      constructor(private hostElement: ElementRef) {
        this.component=hostElement.nativeElement.__component;
      }
    }
    

提交回复
热议问题