如何根据来自后端的数据更改表单中输入开关的状态?

How do I change the status of the inputswitch in the form, depending upon the data from backend?

您好,我是 angular 的新手,我正在使用 primeNg 组件,其中我有一个表单和我有一个 <p-inputswitch> 标签,我有来自后端的 JSON 数据,每条记录都有

{...

"status": "ACTIVE"

....},

状态是活动还是非活动。如果状态为活动,我希望此 inputSwitch 处于开启位置,否则将其保持在关闭位置。 This is what my input switch looks like

还要提一下 - 我有很多 no: 状态为活动或非活动的记录。

这是我输入的formcontrolName

<div class="col-12">
    <p-inputSwitch onLabel="Active" offLabel="Inactive" formControlName="status" ></p-inputSwitch>                                          
</div>

当您通过反应式表单初始化表单时(猜测是这样,因为您使用的是 formControlName)。

your.component.html:

<form [formGroup]="form">
  <p-inputSwitch formControlName="status"></p-inputSwitch>
</form>
<div>
  {{ form.value | json }}
</div>
<button
  (click)="getBackendData()"
  pButton
  pRipple
  type="button"
  label="Get Backend Data"
  class="p-button-raised"
></button>

your.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

export interface BackendData {
  status: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  form: FormGroup;
  mockedBackendData: BackendData = {
    status: 'ACTIVE',
  };

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      status: [false],
    });
  }

  // Only for demonstration purpose
  // Try to never use setTimeout
  // here you put ur async side effect
  // retrieving the data from the backend
  getBackendData() {
    this.mockedBackendData.status =
      this.mockedBackendData.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';

    this.form.patchValue({
      switch: this.mockedBackendData.status === 'ACTIVE' ? false : true,
    });
  }
}

Working Stackblitz

您似乎在使用 ReactiveForms,这是一个很好的方法: component.ts:

@Component({
  selector: 'component',
  templateUrl: './component.html',
  styleUrls: ['./component.scss']
})
export class Component implements OnInit {
  public status: FormControl = new FormControl(false);
  public formGroup: FormGroup = new FormGroup({
    status: this.status
  });
  
  public constructor(private service: Service) { }

  public ngOnInit(): void {
    this.service.getStatus$().subscribe(status => {
      this.status.setValue(status);
      this.status.updateValueAndValidity();
    });
  }
}