javascript - *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">
。
我尝试使用detectChanges
,ngZone
但它仍然无法正常工作。有没有办法切换这个 DOM 元素。提前致谢!
解决方案
似乎您的 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
推荐阅读
- typescript - 泛型方法覆盖多态 this
- java - 如何模拟调用同一类中存在的其他方法的方法
- c# - 有没有更好的方法来堆叠和检查结果?
- android - 如何在 Tink android 中创建主密钥
- mysql - 如何在 Spring Boot 中使用 ST_CONTAINS?
- go - 试图在go中计算pi,我做错了什么?math.Cos 可能有问题?
- javascript - 如何在bot框架版本4 javascript中使用cardImage接口的tap属性
- tensorflow - 哪些语言具有类似于 tensorflow.js 的 Eager API 的 tensorflow 绑定?
- excel - 无法通过使用公式生成 X 坐标和 Y 坐标
- python - 如何将二进制数据重复读入同一个数组?