简体   繁体   English

保存垫子滑动切换的切换状态

[英]Save toggle state of mat slide toggle

I'm using slide-toggle in a aproject.However I am unbale to save the toggled stae.Everytime I refresh the page,the slide toggle returns to default state instead of remaining in the toggled state.I'm new to angular and don't know what to do.Please help.Thanks in advance.我在 aproject 中使用滑动切换。但是我无法保存切换状态。每次刷新页面时,滑动切换都会返回到默认状态而不是保持切换状态。我是 angular 的新手并且不不知道该怎么办。请帮忙。提前致谢。

Here is the ts code:这是ts代码:

export class ToggleComponent implements OnInit {
  @Output()
  change: EventEmitter<MatSlideToggleChange> ;
  @Input()
checked: Boolean 
  ngOnInit() {
  }
  isChecked = true;
  formGroup: FormGroup;
  filteringSchedule: boolean ;
  toggle:Boolean;

  constructor(formBuilder: FormBuilder) {
    this.formGroup = formBuilder.group({
      enableWifi: false,
      acceptTerms: [false, Validators.requiredTrue]
    });
  }

  onFormSubmit(formValue: any) {
    alert(JSON.stringify(formValue, null, 2));
  }

  onChange(ob: MatSlideToggleChange) {
    this.filteringSchedule=!this.filteringSchedule;
    console.log(!this.filteringSchedule);
  } 
}

The template code:模板代码:

<form class="example-form" [formGroup]="formGroup" (ngSubmit)="onFormSubmit(formGroup.value)" ngNativeValidate>
  <mat-action-list>
    <mat-list-item > <mat-slide-toggle  (change)="onChange($event)"  [checked]="filteringSchedule"  formControlName="enableWifi" >Enable Wifi</mat-slide-toggle></mat-list-item> 
    <mat-list-item > <mat-slide-toggle formControlName="acceptTerms">Accept Terms of Service</mat-slide-toggle></mat-list-item>
</mat-action-list>
  <p>Form Group Status: {{ formGroup.status}}</p>

  <button mat-rasied-button type="submit">Save Settings</button>
</form>

Store your toggle property in localStorage and then you can retrieve localStorage value on ngOnInit method.将您的切换属性存储在localStorage ,然后您可以在ngOnInit方法上检索localStorage值。

You can even use sessionStorage based on your requirement.您甚至可以根据需要使用sessionStorage Use of localStorage and sessionStorage is almost identical, you just need to replace one with another. localStoragesessionStorage使用几乎完全相同,您只需将一个替换为另一个。

onChange(ob: MatSlideToggleChange) {
  this.filteringSchedule = !this.filteringSchedule;
  localStorage.setItem('yourKey', JSON.stringify(this.filteringSchedule));
}

ngOnInit() {
  this.filteringSchedule = localStorage.getItem('yourKey') == 'true';
}

Web storages can be used to retain the state of the toggle button (toggled button doesn't change on the page refresh). Web 存储可用于保留切换按钮的状态(切换按钮在页面刷新时不会更改)。

Here I've made aWorking Stackblitz Demo with the code you have provided for your app.在这里,我使用您为应用程序提供的代码制作了一个工作 Stackblitz 演示 I've used local-storage to achieve the desired feature.我已经使用本地存储来实现所需的功能。

Your ToggleComponent is updated below:-您的 ToggleComponent 更新如下:-

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { MatSlideToggleChange } from '@angular/material';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-toggle',
  templateUrl: './toggle.component.html',
  styleUrls: ['./toggle.component.css']
})
export class ToggleComponent implements OnInit {
  @Output() change: EventEmitter<MatSlideToggleChange>;
  @Input() checked: boolean;

  isChecked = true;
  formGroup: FormGroup;
  filteringSchedule: boolean;
  toggle: boolean;

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.filteringSchedule = JSON.parse(localStorage.getItem('toggleButtonState'));
    this.formGroup = this.formBuilder.group({
      enableWifi: this.filteringSchedule,
      acceptTerms: [false, Validators.requiredTrue]
    });
  }

  onFormSubmit(formValue: any) {
    alert(JSON.stringify(formValue, null, 2));
  }

  onChange(ob: MatSlideToggleChange) {
    this.filteringSchedule = !this.filteringSchedule;
    localStorage.setItem('toggleButtonState', JSON.stringify(this.filteringSchedule));
  }
}

Also note:- To be consistent for the user across all browsers in addition (or instead of) to storing toggled state of the button in cookies/local storage you can store it server side and when loading the site get the info about the toggled button state from the server.另请注意:-除了(或代替)将按钮的切换状态存储在 cookie/本地存储中之外,为了使所有浏览器的用户保持一致,您可以将其存储在服务器端,并在加载站点时获取有关切换按钮的信息来自服务器的状态。

On a side note form builder code, you have placed inside the constructor should be kept inside ngOnInit , to avoid performance issues with the app.在旁注表单构建器代码中,您放置在构造函数中的应保留在ngOnInit ,以避免应用程序出现性能问题。

Hope this is helpful.希望这是有帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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