Veto
Veto

Reputation: 165

Get reference to element inside ng-template

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.

Upvotes: 13

Views: 12002

Answers (2)

Venkatesh Muniyandi
Venkatesh Muniyandi

Reputation: 5640

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

@ContentChild('newimg') img: ElementRef;

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657801

<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.

Upvotes: 4

Related Questions