Get reference to element inside ng-template

Viewed 8950

this is my template:

<ng-template #template>
    <input #newimg  type="file" class="col-md-10" (change)="fileChange($event)"/>
</ng-template>

I cant get reference to #newimg when its inside ng-template(it works fine if i change ng-template to div!)

@ViewChild('newimg') img: ElementRef; //doesnt work

I need to set its value to empty after image uploaded but its always undefined.

2 Answers

<ng-template> is not added to the DOM, it exists only in JavaScript code, when the Application runs. Only when it is stamped using for example a structural directive like *ngFor or *ngIf, the content is actually created in the DOM and bindings, components, directives, ... are instantiated.

Therefore without stamping, there won't be any #template to query for.

Use ContentChild instead of ViewChild, because your template reference is within a projected content (ngtemplate)

@ContentChild('newimg') img: ElementRef;
Related