Structural directive - finding the element it is placed on

前端 未结 4 1814
闹比i
闹比i 2021-02-07 05:25

With a structural directive, how would I get a hold of the (native) element the directive is on? With a normal directive, the ElementRef has it\'s nativeElement pointing to it -

相关标签:
4条回答
  • 2021-02-07 05:30

    This isn't pretty, but worked for me:

    this.viewContainer.get(0).rootNodes[0]
    

    I used it when implementing a version of *ngIf directive but with animation: animatedIf.

    0 讨论(0)
  • 2021-02-07 05:39

    Based on the Structural Directives Documentation (not sure if it works, but maybe helps you):

    <input type="text" *example>
    
    
    @Directive({
      selector: '[example]'
    })
    export class ExampleDirective {
    
      constructor(private viewContainer: ViewContainerRef) { }
    
      @Input() set example() {
        console.log(this.viewContainer.element.nativeElement.value);
      }
    }
    
    0 讨论(0)
  • 2021-02-07 05:50

    All structural directives are added to <ng-template> elements. Angular never adds <ng-template> elements to the DOM. Therefore it's not possible to get the element a structural directive is added to.

    If you use the shorthand syntax with * like

    <div *ngIf="..."></div>
    

    angular creates

    <ng-template [ngIf]="...">
      <div></div>
    </ng-template>
    

    and because <ng-template> is not added, there is no way of getting it and because <div> is not the element the structural directive is added to you also can't get this element using the directive reference.

    0 讨论(0)
  • 2021-02-07 05:55

    When the structural directive is used on HTMLElement, you will not get the reference to that element, as it is not rendered yet. The input text box is not rendered yet when you are trying to access it in your code console.log(this.el.nativeElement); // template bindings comment

    Please refer the link below to know how structural directives in Angular work. https://angular.io/guide/structural-directives#the-asterisk--prefix

    So to get the reference of the element, you can use attribute directive on the same element and do the things needed.

    0 讨论(0)
提交回复
热议问题