简体   繁体   中英

Binding click event inside template with plain javascript as value in angular2

In this template, in first li element, I want to bind (click) event to store some values in localStorage. I am not getting any error but its not working. Iam trying to access this 'someStatus' in some other component using localStorage.getItem('someStatus') but Iam not getting the stored value on click. Please suggest me correct approach. Thank you.

import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute, NavigationEnd, Params, PRIMARY_OUTLET } from "@angular/router";
@Component({
selector: 'breadcrumb',
template: `<div id="crumbs">
<ul>
    <li routerLinkActive="active" (click)="localStorage.setItem('someStatus',false)"><a routerLink="/page1">Option 1</a></li>
    <li routerLinkActive="active"><a routerLink="/page2" title="Summary">Option 2</a></li> 
</ul>
</div>`
})
export class BreadcrumbComponent implements OnInit {constructor(  ) {  }  ngOnInit() {  }}

As mentioned in the Angular documentation , you don't have access to global methods and objects (like localStorage ) in the template:

Template expressions cannot refer to anything in the global namespace (except undefined). They can't refer to window or document. They can't call console.log or Math.max. They are restricted to referencing members of the expression context.


You can put the code in a method of the component:

public resetSomeStatus(): void {
    localStorage.setItem('someStatus', false);
}

and call that method in your click event:

<li routerLinkActive="active" (click)="resetSomeStatus()">

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