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

Issue

Hi I am new to angular and I am using primeNg components in which I have a form and in my form I have a <p-inputswitch> tag and I have my JSON data coming from the backend and each record has

{...

"status": "ACTIVE"

....},

either the status is active or inactive. I want this inputSwitch to be in ON position if the status is Active else keep it in Off Position.
This is what my input switch looks like

Also to mention – I have many no: of records which have status active or inactive.

This is my input formcontrolName

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

Solution

When you init the form via reactive forms (guess so since you are using 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

Answered By – sagat

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published