如何在不使用纯JavaScript的情况下操作TemplateRef中的DOM元素

时间:2018-08-08 06:19:22

标签: angular6

我在Component类中有这个模板

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

当使用者从input元素中选择图像文件时,我想显示图像的缩略图。我可以使用纯JavaScript代码(createElementsetAttributeaddEventListener等来做到这一点,但我想我不应该在{{1}中混合使用JS代码}。因此,我计划使用AngularViewChildRenderer2ViewContainer)。

到目前为止,我已经了解了模板和视图容器的引用。

TemplateRef

但是我不知道如何访问模板内的@ViewChild("thumbnailContainer",{read:ViewContainerRef}) thumbnailContainerRef:ViewContainerRef; @ViewChild("thumbnailTemplate",{read:TemplateRef}) thumbnailTemplateRef:TemplateRef<null>; @ViewChild("image-thumbnail-container",{read:ElementRef}) imageThumbnailContainer:ElementRef; divimg?由于用户可以选择多个文件,因此a可以包含ViewContainer中的多个Views。因此,我想给TemplateRefdiv提供不同的a,并设置ids Renderer2 src nativeElement {{1}的img. I suppose I can use } div APIs to set the attributes but for that I need to pass img of the a , nativeElement`,因为它们位于模板中。

0 个答案:

没有答案