代码之家  ›  专栏  ›  技术社区  ›  mehul

如何在ngif中使用localstorage值

  •  1
  • mehul  · 技术社区  · 8 年前

    我需要在 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;
    }
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   codeepic zetriks    8 年前

    首先,你的 readLocalStorageValue(key) 太复杂了。

    您只需使用:

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

    第二,如果不需要,不要在模板中使用函数,因为角度变化检测会导致它们执行多次。当您的控制台日志被多次打印时,您可能已经看到了它。所以你应该存储 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-template 你应该什么时候用 ng-container . 用 NG模板 标记您定义了一个模板,但不使用它,所以不会呈现任何内容。你想用什么 *NGIF 天然气容器

    我知道这很混乱,所以最好查一下这个帖子 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>
    
        2
  •  0
  •   li x    8 年前

    我想你可以* ngIf='localStorage.getItem(key) === "admin"' 直接从你的 ngIf 因为它将与您当前的 readLocalStorageValue() 方法,以及在本地存储更新时进行更改。

    或者,您可以使用服务和 behavior subject 通过注入进入组件状态。

    @Injectable()
    export class LocalStorageService {
    
        private subject = new Subject<any>();
    
        notifyLocalComponents(message: string) {
            this.subject.next({text: message});
        }
    
        getMessage(): Observable<any> {
            return this.subject.asObservable();
        }
    
    }
    

    上面的服务是您构建逻辑以更新行为主题中的本地存储值的地方。然后您可以订阅如下更改:

        constructor(private storageService: LocalStorageService){
           this.storageService.getMessage().subscribe(()=>{ // Update local state here when an update has been found. });
        }
    
        3
  •  -1
  •   Mahesh G    8 年前

    这是我的方法,我还建议使用观察项来继续监听本地存储的更改。

    Demo

    注意:在演示中,我添加了行 localStorage.setItem('role', "admin"); 在ngoninit中手动添加角色为admin,您可以验证只有当角色设置为admin时,才会显示DIV元素,否则不会显示。

    成分

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      checkStatus: boolean;
    
      public localStorageItem(): boolean {
        if (localStorage.getItem("role") === "admin") {
          return true
        } else {
          return false;
        };
      }
      ngOnInit() {
        this.checkStatus = this.localStorageItem();
      }
    }
    

    HTML

    <div *ngIf="checkStatus">
      .
      .
    <div>
    
    推荐文章