【问题标题】:I want to disable the button even after refreshing the page即使在刷新页面后我也想禁用该按钮
【发布时间】:2019-04-27 13:25:15
【问题描述】:

我有一组命名人员的对象。我正在尝试禁用该按钮,即使在刷新页面后仍应保持禁用状态。请帮忙

    <div *ngFor="let item of people">
      <button [disabled]="item.disabled"(click)="item.disabled=true">Hi</button> 
    </div>

【问题讨论】:

  • 然后您需要保存并获取people,例如使用localStorage
  • 你可以向人们发布 JSON 并且你使用任何后端吗?

标签: angular angular6


【解决方案1】:

刷新页面类似于重新启动单页 Web 应用程序。刷新时,默认情况下会重置组件和对象状态。 如果您希望对象状态在刷新后仍然存在,您只需通过本地或会话存储来存储它,或者从 OnInit 的外部服务中获取它

【讨论】:

    【解决方案2】:

    试试localStorage:

    HTML 代码:

    <div *ngFor="let item of people">
      <button  mat-stroked-button color="primary" [disabled]="item.disabled" (click)="disableItem(item)">Hi</button>      
    </div>
    
    <button mat-stroked-button color="primary" (click)="reset()">Reset</button>
    

    TS 代码:

    import { Component } from '@angular/core';
    
    export interface Section {
      name: string;
      updated: Date;
    }
    
    /**
     * @title List with sections
     */
    @Component({
      selector: 'list-sections-example',
      styleUrls: ['list-sections-example.css'],
      templateUrl: 'list-sections-example.html',
    })
    export class ListSectionsExample {
      people: any[] = [
        {
          name: 'Photos',
          updated: new Date('1/1/16'),
        },
        {
          name: 'Recipes',
          updated: new Date('1/17/16'),
        }
      ];
    
      constructor() {
        this.people = JSON.parse(localStorage.getItem('people'));
      }
    
      reset() {
        this.people = [
          {
            name: 'Photos',
            updated: new Date('1/1/16'),
          },
          {
            name: 'Recipes',
            updated: new Date('1/17/16'),
          }
        ];
        localStorage.setItem('people', JSON.stringify(this.people))
      }
    
      disableItem(data) {
        data.disabled = true;
        localStorage.setItem('people', JSON.stringify(this.people))
      }
    }
    

    Working Demo

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多