在 angular2 中使用纯 javascript 作为值在模板内绑定点击事件

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

在此模板中,在第一个 li 元素中,我想绑定(单击)事件以将一些值存储在 localStorage 中。我没有收到任何错误,但它不起作用。我正在尝试使用 localStorage.getItem('someStatus') 在其他一些组件中访问此 'someStatus' 但我没有在单击时获取存储值。请建议我正确的方法。谢谢你。

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() {  }}

Angular documentation 中所述,您无权访问模板中的全局方法和对象(如 localStorage):

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.


您可以将代码放在组件的方法中:

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

并在您的点击事件中调用该方法:

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