首页 > 解决方案 > *ngIf 不使用 eventListener 触发内部服务

问题描述

我有一个label这样的渲染*ngIf

<label for="file-8" id="upload-area" *ngIf="isAllowUpload">
    <input type="file" id="file-8" accept="image/*"  style="display: none;" (change)="onFileChanged($event)">
    <div class="empty-image-input">
       <img src="assets/static/media/plus-sign.svg" alt="icon" width="18" height="18">
    </div>
</label>

onFileChanged 函数:

onFileChanged(event: any) {
    this.files = event.target.files;
    this.onUpload();
}

上传功能:

private onUpload() {
    const formData = new FormData();
    for (const file of this.files) {
      formData.append("file", file, file.name);
    }
    const self = this;
    this._service.uploadImage(formData)
    .pipe(finalize(() => {}))
    .toPromise()
    .then((info: any) => {
         this.isAllowUpload = false;
         this.cdRef.detectChanges();
         var container = document.getElementById('image-container');
         container.innerHTML += `
             <label id="image0">
                <div class="image-container">
                    <button type="button" id="delete-image"> </button>
                    <img src="` + info + `">
                </div>
            </label>
        `;
        document.getElementById('delete-image').addEventListener('click', function () {
           this.isAllowUpload = true;
           this.zone.run(() => this.isAllowUpload = true)
           this.cdRef.detectChanges();
        })
    })
}

这意味着当服务完成加载数据时,会创建一个 html 内容并附加到<div id="image-container">. <label>DOM 是隐藏的,因为isAllowUpload = false(它仍然有效)。之后,我addEventListener在 click 时创建了那个 catch 事件<button id="delete-image">。单击按钮时,会触发事件并isAllowUpload更改值,但不会重新渲染视图<label id="upload-area">

我尝试使用detectChangesngZone但它仍然无法正常工作。有没有办法切换这个 DOM 元素。提前致谢!

标签: javascriptangulartypescript

解决方案


似乎您的 stackblitz 实例中的 HTML 存在问题。您正在使用字符串覆盖 HTML 的内容,并且您的实际绑定不再存在。

在追加数据的地方保持 div 分开。请看下面:

<div>
    <!-- wrap div where you want to append image. -->
    <div class="property-content" id="image-container">
    </div>
    <label for="file-8" id="upload-area" *ngIf="isAllowUpload">
                  <input type="file" id="file-8" accept="image/*"  style="display: none;" (change)="onFileChanged($event)">
                  <div class="empty-image-input">
                    <img src="https://img.icons8.com/flat_round/64/000000/plus.png" alt="icon" width="18" height="18">
                  </div>
                </label>
    <p *ngIf="isAllowUpload">allow upload</p>
</div>

请在 stackblitz 中找到工作链接:https ://stackblitz.com/edit/angular-xld2in


推荐阅读