![](/img/trans.png)
[英]Angular 8 using ngIf with async pipe to show and hide the HTML element
[英]Angular *ngIf with async pipe inner condtion based on the resulting model
如果有人能解釋為什么以下內容沒有按預期工作,我會是一個快樂的人嗎? hasCreative
是一個布爾值,但不管它的真/假值如何,總是顯示<li>
。 任何建議都會很棒。 謝謝你。
<ng-container *ngIf="uiModel$ | async as model">
<ul class="nav" style="padding-bottom: 30px;">
<li *ngIf="model.hasCreative" class="nav-item">
<a class="nav-link active" routerLinkActive="active" [routerLink]="['']">Home</a>
</li>
</ul>
</ng-container>
export class UserInterfaceModel {
hasCreative: boolean;
}
@Injectable({
providedIn: 'root'
})
export class UserInterfaceService {
user: CognitoUser;
userLoggedIn = false;
private userInterfaceModelSubject$: Subject<UserInterfaceModel> = new Subject();
userInterfaceModel$ = this.userInterfaceModelSubject$.asObservable();
constructor(private authService: AuthService) {
combineLatest([this.authService.onUserLoaded$]).subscribe(([currentUser]) => {
this.user = currentUser;
this.userLoggedIn = true;
this.buildUserInterfaceModel();
});
}
buildUserInterfaceModel(){
const model = new UserInterfaceModel();
if (this.userLoggedIn && this.user !== null){
model.hasCreative = this.user.getSignInUserSession().getIdToken().payload.creative;
}
this.userInterfaceModelSubject$.next(model);
}
}
嘗試使用這個:
<ng-container *ngIf="uiModel$ | async as model; else loading">
<ul class="nav" style="padding-bottom: 30px;">
<li *ngIf="model.hasCreative === true " class="nav-item">
<a class="nav-link active" routerLinkActive="active" [routerLink]="['']">Home</a>
</li>
</ul>
</ng-container>
<ng-template #loading>
Loading stuff...
</ng-template>
如果loading
模板將呈現,則意味着您的Observable
沒有價值。 如果它也不起作用,請嘗試通過添加如下model.hasCreative
來渲染model.hasCreative
的值:
<span>{{model.hasCreative}}<span>
從<ul>
標簽中查看model.hasCreative
是否具有true/false
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.