How to manipulate DOM elements inside a TemplateRef without using pure javascript

假如想象 提交于 2019-12-11 15:18:51

问题


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.

来源:https://stackoverflow.com/questions/51739779/how-to-manipulate-dom-elements-inside-a-templateref-without-using-pure-javascrip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!