【问题标题】:Checkbox dont stay checked when changing component in Angular 8在Angular 8中更改组件时复选框不保持选中状态
【发布时间】:2020-01-13 12:29:00
【问题描述】:

即使我离开我的组件,我也试图检查我的复选框列表。 问题是我什至可以成功保存选中的复选框,但是当我离开组件并返回时,它们不会保持选中状态,我不知道我错过了什么

这是我的按钮,里面有复选框。

<mat-button-toggle-group class="row"
                         name="payments">
    <mat-button-toggle class="col">
        <button type="button"
                [ngClass]="{'clicked': toggleState}"
                class="payment-button"
                (click)="togglePayments()">
            <mat-icon aria-label="{{'csa.payments-title' | translate}}">payments</mat-icon>
            <mat-icon>keyboard_arrow_down</mat-icon>
        </button>

        <div *ngIf="show"
             class="toggle-checkbox">
            <mat-checkbox *ngFor="let payment of payments"
                          class="col"
                          [value]="payment"
                          [checked]="paymentState[payment]"
                          (change)="onPaymentsChange($event, payment)"
                          [class.show]="show">
                {{payment | translate}}
            </mat-checkbox>
        </div>
    </mat-button-toggle>
</mat-button-toggle-group>
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'
import { ICategory, ICategoryDto } from '@app/api/models/api-models'

@Component({
  selector: 'payments-button',
  templateUrl: 'payments-button.component.html',
  styleUrls: ['./payments-button.component.scss'],
})
export class PaymentsButtonComponent implements OnInit {
  @Input() payments: ICategory[]
  // @Output() getChecklist: EventEmitter<any> = new EventEmitter()

  show = false
  paymentState: { [key: string]: boolean }

  constructor() {
    this.paymentState = {}
  }

  ngOnInit() {
    console.log('payments', this.payments)
    /* if (this.payments) {
      this.payments.forEach((payment: string) => {
        console.log(payment)
      })
    } */
    this.payments.forEach((payment: ICategory) => {
      this.paymentState[payment.name] = false
    })
  }

  togglePayments() {
    this.show = !this.show
  }

  /**
   * When users check/unckeck some payments.
   * @param event click event
   * @param payment payment selected
   */
  onPaymentsChange(event, payment: string) {
    this.paymentState[payment] = !this.paymentState[payment]
    // this.getChecklist.emit(this.paymentState[payment])
  }
}

这就是我调用组件的方式

<payments-button [payments]="this.categoriesAndCountries.payments"
                                                     (getChecklist)="onChecked($event)">
                                    </payments-button>

getChecklist 除了返回 true 或 false 之外没有做任何事情。 https://imgur.com/a/KyzSArF 当我单击基本数据时,支票将返回为空 对我缺少什么有任何帮助吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    但是当我离开组件并回来时,它们不会保持检查状态

    这是因为您在组件中保留了付款状态,这也意味着当您的组件被销毁时,您丢失您的组件拥有的所有数据。

    解决此问题的一种方法是将状态存储在服务中

    paymentState.service.ts

    paymentState: { [key: string]: boolean }
    
    this.paymentState = {}
    
    setPaymentItemState (item, value) {
        this.paymentState[item] = value;
    }
    

    payment-button.component.ts

    get paymentState () {
        return this.paymentStateService.paymentState;
    }
    
    constructor (private paymentStateService: PaymentStateService) { }
    
    /* ... */
    
    onPaymentsChange(event, payment: string) {
        this.paymentStateService.setPaymentItemState(payment, !this.paymentState[payment])    
    }
    
    /* ... */
    

    【讨论】:

    • 但是使用服务我如何获得服务的 Checked 值? ``` [checked]="paymentState[payment]" ```
    • 通过使用 setPaymentItemState 方法。
    【解决方案2】:

    请参阅有关路线状态的角度文档,因为您想在离开后保存上一条路线的状态。 https://angular.io/guide/router#router-state

    或者,您可以检查此解决方案: Angular 4: Save component state after routing to another component

    第三个选项是在每个选定选项处创建一个将选择状态保存在数据库中的服务。 为了更容易制作原型,我建议你使用InMemoryDbService

    【讨论】:

    • 但是使用服务我如何获得服务的 Checked 值? ``` [checked]="paymentState[payment]" ```
    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 2012-08-25
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多