0

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 useRenderer2APIs to set the attributes but for that I need to passnativeElementof thediv,imgandato it. But I don't know how to getnativeElement` of these as they are inside a template.

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • can't you place them and change their behaviour with ngIf? – firegloves Aug 08 '18 at 16:09
  • sorry, I didnt understand what mean. I want that if I place the template at 3 places then for each instance of the template, I provide different values of `src` attribute of `img`. I don't know how `ngIf` would help. – Manu Chadha Aug 08 '18 at 18:13
  • Possible duplicate of [how to delete a specific view from viewcontainer angular](https://stackoverflow.com/questions/51764692/how-to-delete-a-specific-view-from-viewcontainer-angular) – Manu Chadha Aug 09 '18 at 15:37

0 Answers0