我有一个由*ngIf呈现的label,如下所示:
<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();
}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">。因为isAllowUpload = false(它仍然有效),<label> DOM被隐藏了。在那之后,我创建了在单击<button id="delete-image">时捕获事件的addEventListener。当单击按钮时,事件被激发,isAllowUpload改变了值,但视图不会重新呈现<label id="upload-area">。
我尝试使用detectChanges和ngZone,但仍然不起作用。有没有办法切换这个DOM元素。提前感谢!
发布于 2020-03-07 18:10:26
看起来像是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
发布于 2020-03-07 15:53:08
请尝试使用以下方法。
this.cdRef.markForCheck();https://stackoverflow.com/questions/60575261
复制相似问题