Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structural directive - finding the element it is placed on

Tags:

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 - eg:

<input type="text" example>

@Directive({
  selector: '[example]'
})
export class ExampleDirective {    

  constructor( private el: ElementRef) {}

  ngAfterViewInit() {
    console.log(this.el.nativeElement); // the input
  }
}

But with a structural directive, it points to the template comment - eg.

<input type="text" *example>

@Directive({
  selector: '[example]'
})
export class ExampleDirective {

  constructor(
    private el: ElementRef,
    private view: ViewContainerRef,
    private template: TemplateRef<any>
  ) {}

  ngAfterViewInit() {
    this.view.createEmbeddedView(this.template);

    console.log(this.el.nativeElement); // template bindings comment
    // how to find the input itself?
  }
}

I've tried using various combinations of ViewContainerRef, TemplateRef, @ContentChild, @ViewChild - just don't seem to be able to find the input element itself...

like image 424
Calv J Avatar asked Dec 23 '16 09:12

Calv J


People also ask

How many structural directives can you place on an element?

You may apply only one structural directive to an element.

How do you use structural directives?

These directives work by using the HTML 5 <ng-template> tag. This is a new tag in HTML which is specifically designed to hold template code. It can sit under the body element but any content inside it is not shown in the browser. This is the NgFor directive itself.

Which among the following is the Angular structural directive to check the existence of a value?

1. *ngIf: ngIf is used to display or hide the DOM Element based on the expression value assigned to it. The expression value may be either true or false.

Are structural directives easy to recognize?

As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendents. Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.


1 Answers

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.

like image 165
Günter Zöchbauer Avatar answered Nov 16 '22 07:11

Günter Zöchbauer