gpt4 book ai didi

angular - 如何在 ngif 中使用本地存储值

转载 作者:行者123 更新时间:2023-12-04 02:58:29 26 4
gpt4 key购买 nike

我需要在 ngif 中使用本地存储值..

怎么办..我试了各种方法都搞不定..

下面附上我的代码

<ng-template *ngIf="readLocalStorageValue('Role')== 'admin'">

<button
class="btn btn-primary editable-table-button btn-xs"
(click)="updatetq(tq_list.cmslearntopicid, tq_list.cmslearnchapterid,tq_list.topicname);"
>Edit</button>

<button
class="btn btn-danger editable-table-button btn-xs"
(click)="deletet(tq_list.cmslearntopicid);"
>Delete</button>

</ng-template>

下面还有ts文件:当我打印值然后它显示管理员但随后它也不起作用......

需要帮助..有人可以帮助我吗

readLocalStorageValue(key) {
let value = localStorage.getItem(key);
console.log("-------"+value);

if(value == undefined) {
value =='';
}
return value;
}

最佳答案

首先,您的 readLocalStorageValue(key) 过于复杂。

你可以只使用:

readLocalStorageValue(key) {
return localStorage.getItem(key);
}

其次,如果没有必要,不要在模板中使用函数,因为 Angular 变化检测会导致它们执行多次。当您的控制台日志被多次打印时,您可能已经看到了。因此,您应该将 readLocalStorageValue 方法的结果存储在 role 之类的变量中,并使用该变量代替带有 *ngIf 的模板中的方法

此处有更多关于该主题的信息 https://blog.appverse.io/why-it-is-a-bad-idea-to-use-methods-in-the-html-templates-with-angular-2-30d49f0d3b16

第三。当您应该使用 ng-container 时,您正在使用 ng-template。使用 ng-template 标签,您定义了一个模板,但您不使用它,因此不会呈现任何内容。您想要与 *ngIf 一起使用的是 ng-container

我知道这很困惑,所以最好查看这篇文章 https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

你的组件代码应该是:

role: string;

ngOnInit(){
this.role = this.readLocalStorageValue('Role');
}

readLocalStorageValue(key: string): string {
return localStorage.getItem(key);
}

您的模板代码应该是:

<ng-container *ngIf="role==='admin'">

<button class="btn btn-primary editable-table-button btn-xs" (click)="updatetq(tq_list.cmslearntopicid
,tq_list.cmslearnchapterid,tq_list.topicname);">Edit</button>

<button class="btn btn-danger editable-table-button btn-xs" (click)="deletet(tq_list.cmslearntopicid);">Delete</button>

</ng-container>

关于angular - 如何在 ngif 中使用本地存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521696/

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