简体   繁体   中英

How to get localStorage value in Angular 2 template

Here is my code,

HTML:

<div *ngFor="let comment of comments | orderBy: '-'+orderBy">
    <div class="comment-item">
        <div class="row">
            <div class="col-md-8">
                {{comment.userName}}
            </div>
            <div class="col-md-4">
                <div class="comment-timeago">
                    {{comment.time | timeAgo}}
                </div>
                <div class="likedicon">
                    <i class="fa fa-heart-o disliked" aria-hidden="true" (click)="likeComment(comment._id, comment)"></i>
                    <i class="fa fa-heart liked" aria-hidden="true" *ngIf="comment.liked == 'liked'" (click)="dislikeComment(comment._id, comment)"></i>
                </div>
                <div class="like-num">
                    {{comment.like}}
                </div>
            </div>
        </div>
    </div>
</div>

File component.ts:

likeComment(commentId, comment) {

    localStorage[commentId] = "liked";
    comment.liked = localStorage[commentId];
    comment.like ++;
    this.dataService.likeComment(commentId).subscribe(
        // Post data to server
        error => console.log(error)
    )
}

dislikeComment(commentId, comment) {
    localStorage[commentId] = "disliked";
    comment.liked = localStorage[commentId];
    comment.like --;
    this.dataService.dislikeComment(commentId).subscribe(
        // Post data to server
        error => console.log(error)
    )

Every comment can switch liked or disliked independently, but I have to use localStorage to decide what status should display. Maybe like:

*ngIf="localStorage.getItem(comment._Id) == 'liked'"

Unfortunately, it's the wrong syntax. I find the getter working on my other case, and the reference is from Angular2 How to display localStorage value inside HTML5 template? .

In this case, I have no idea to do that, because I can't use get commentLike() in my function, neither use a global variable. How do I solve it?

When you are trying to use *ngIf="localStorage.getItem(comment._Id) == 'liked'" it's trying to find this.localStorage in component.ts, but it doesn't exist, so it's throwing an error... Things like localStorage is common to use wherever required so keep it in global.ts which can be accessed easily...

In your global.ts , add a function like this:

export class GlobalApp {

constructor() {}

public localStorageItem(id: string): string {
    return localStorage.getItem(id);
}

Now update your component.ts :

import {GlobalApp} from '../helpers';

export class MyComponent {

constructor (public app: GlobalApp)  {
  }
}

Now it's ready to easily use in any template as we have a global declared function:

*ngIf="app.localStorageItem(comment._Id) == 'liked'"

It is not the correct way to use localStorage like localStorage[commentId] . You should check it here: Window.localStorage .

You should use setItem and getItem.

For your case, I suggest you to use module marcj/angular2-localstorage .

In component:

@LocalStorage() public comments:any = [];

In your template:

*ngIf="comments[index]._id == 'liked'"
@Component({
 selector:'app-any',
 templates:`<div *ngIf="localStorageAlice.getItem('key')">...</div>`
})
export class MyComponent {

 localStorageAlice = localStorage; 
 // to access localStorage in html use localStorageAlice.getItem('key');
}

Alternatively you can use like this

In your component:

*ngIf="getItem(comment._Id) == 'liked'"

In your template:

getItem ( item ) { 
       return localStorage.getItem(item)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM