Angular 如果/否则更改,则检测角度模板
我有一个使用Angulars条件模板逻辑来显示动态内容的模板。条件的值根据异步函数的响应而变化。在函数返回一个值之后,我想添加一个新元素。问题是,当我这样做时,新元素会在模板更改之前追加,从而有效地删除追加的元素 以stackblitz为例: 应用程序组件.tsAngular 如果/否则更改,则检测角度模板,angular,ng-template,angular-changedetection,Angular,Ng Template,Angular Changedetection,我有一个使用Angulars条件模板逻辑来显示动态内容的模板。条件的值根据异步函数的响应而变化。在函数返回一个值之后,我想添加一个新元素。问题是,当我这样做时,新元素会在模板更改之前追加,从而有效地删除追加的元素 以stackblitz为例: 应用程序组件.ts export class AppComponent implements AfterViewInit { private hasAsyncResponded; private p: HTMLParagraphElement;
export class AppComponent implements AfterViewInit {
private hasAsyncResponded;
private p: HTMLParagraphElement;
async ngAfterViewInit() {
this.hasAsyncResponded = await this.getAsyncThing();
this.p = document.createElement('p');
this.p.textContent = 'foo bar baz';
document.getElementsByClassName('my-div')[0].appendChild(this.p);
// debugger;
}
get shouldShowTemplateTwo(): boolean {
return this.hasAsyncResponded ? true : false;
}
async getAsyncThing(): Promise<boolean> {
const promise: Promise<boolean> = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, 3000);
});
return promise;
}
}
导出类AppComponent实现AfterViewInit{
私人医院;
私有p:HTMLParagraphElement;
异步ngAfterViewInit(){
this.hasaAsyncResponsed=等待this.getAsyncThing();
this.p=document.createElement('p');
this.p.textContent='foo-bar-baz';
document.getElementsByClassName('my-div')[0].appendChild(this.p);
//调试器;
}
get-shouldShowTemplateTwo():布尔值{
返回this.hasAsyncResponsed?true:false;
}
异步getAsyncThing():承诺{
持续承诺:承诺=新承诺((解决、拒绝)=>{
设置超时(()=>{
决心(正确);
}, 3000);
});
回报承诺;
}
}
app.component.html
<ng-container *ngIf="shouldShowTemplateTwo; then templateTwo else templateOne"></ng-container>
<ng-template #templateOne>
<div class="my-div">
<h1>Template 1</h1>
</div>
</ng-template>
<ng-template #templateTwo>
<div class="my-div">
<h1>Template 2</h1>
</div>
</ng-template>
模板1
模板2
在app.component.ts的第9行,我定义了一个名为hasAsyncResponsed
的变量,该变量默认为falsy(未定义)
在第13行,我等待异步函数的响应,并将其存储为hasasyncresponsed
的值
在第20行,我创建了一个getter,模板使用该getter有条件地显示所需的ng模板
(app.component.html:第1行)
承诺解析后,hasaAsyncResponsed
的值设置为true,从而切换ng模板。同样,在承诺解决后,我们进入app.component.ts的第16行,该行在模板中添加了一个新段落
<ng-container *ngIf="yourPromise | async; then templateTwo else templateOne">
由于承诺已经解决,并且在添加新段落之前,hasaAsyncResponsed
的值已经更新,因此我希望新段落能够添加到更新的模板(#templateTwo
)中。但是,段落会附加到前一个模板(#templateOne
)。如果在app.component.ts的第17行取消对调试器的注释,则可以看到这一点。当调试器暂停代码执行时,将显示随附段落显示的#templateOne
,恢复代码执行后将显示#templateTwo
如何将段落附加到正确的模板中?我想,也许我只需要在添加新段落之前检测变化,但这并不能起作用 这就是异步管道的用途,将承诺分配给组件上的属性,并在模板中使用异步管道
<ng-container *ngIf="yourPromise | async; then templateTwo else templateOne">
无需签署打字稿中的承诺,我最终认为我把问题复杂化了
我创建了一个新属性shouldShowTemplateTwo
,该属性默认为false,并在等待的承诺解决时设置为true