gpt4 book ai didi

javascript - 为什么 ngOnInit 变量更改不会影响 Angular 2/4 中的 html?

转载 作者:行者123 更新时间:2023-12-03 04:15:18 24 4
gpt4 key购买 nike

我有我正在订阅的用户对象。如果用户等于某个名称,则不应显示按钮。我不知道为什么它不影响html中的ngIf。

我的 HTML

 <input *ngIf = "showDelete" type = "button" (click) = 
"deleteCustomer(customer._id)" value = "Delete" class = "btn btn-danger">

appcomponent.ts 中我的 ngOnInit

    ngOnInit() {

let showDelete:boolean =true;

this.authService.getProfile().subscribe(profile => {
this.username = profile.user.name

if (this.username=="admin"){

showDelete=false;
}
},

如果我 console.log this.username 并显示删除,我会得到预期的值,但它不会改变 html 中的逻辑

最佳答案

您应该将 showDelete 变量声明为组件的一部分,以便可以从模板访问它:

public showDelete: boolean = true;

ngOnInit(): void {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.name;
if (this.username == "admin") {
this.showDelete = false;
}
});
}

关于javascript - 为什么 ngOnInit 变量更改不会影响 Angular 2/4 中的 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44168149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com