I have this template in my Component class
<ng-template #thumbnailTemplate>
<div> <!-- top level div of thumbnail. This will have ids thumbnail-1, thumbnail-2 etc.-->
<img> <!-- this will have width, height=80-->
<a></a> <!-- the X button is created using CSS. This will have ids close-button-1, close-button-2. They'll also containn reference to the parent div id (thumbnail-1, thumbnail-2 ) -->
</div>
</ng-template>
<div class="form-group">
<div class="custom-file" id="file-upload" lang="es">
<input type="file" class="custom-file-input" id="question-file-upload" formControlName="image" [ngClass]="validateField('image')" (change)="handleFileSelect($event)" required>
<label class="custom-file-label" for="question-file-upload">
Select file...
</label>
</div>
<div id="image-thumbnail-container">
<ng-container #thumbnailContainer ></ng-container> <!-- This will contain the view created from #thumbnailTemplate. It can have multiple thumbnails. Check .ts file-->
</div>
</div>
</div>
When the use selects an image file from input
element, I want to show a thumbnail of the image. I am able to do this using pure javascript code (createElement
, setAttribute
, addEventListener
etc.) but I suppose I shouldn't mix JS
code in Angular
. So I plan to use ViewChild
, Renderer2
, ViewContainer
and TemplateRef
).
So far, I have got to the point where I have got reference of the template and the view container.
@ViewChild("thumbnailContainer",{read:ViewContainerRef}) thumbnailContainerRef:ViewContainerRef;
@ViewChild("thumbnailTemplate",{read:TemplateRef}) thumbnailTemplateRef:TemplateRef<null>;
@ViewChild("image-thumbnail-container",{read:ElementRef}) imageThumbnailContainer:ElementRef;
But I don't know how to get access to the div
, img
and a
inside the template? As a user can select multiple files, the ViewContainer
can have multiple Views
of the TemplateRef
. So I want to give the div
and a
different ids
and also set the src
of the img. I suppose I can use
Renderer2APIs to set the attributes but for that I need to pass
nativeElementof the
div,
imgand
ato it. But I don't know how to get
nativeElement` of these as they are inside a template.