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 >
<p-inputSwitch onLabel="Active" offLabel="Inactive" formControlName="status" ></p-inputSwitch>
</div>
CodePudding user response:
When you init the form via reactive forms (guess so since you are using formControlName).
your.component.html:
<div >
<!-- Formgroup directive necessary to bind to reactive form -->
<form [formGroup]="form">
<p-inputSwitch onLabel="Active" offLabel="Inactive"
formControlName="status"></p-inputSwitch>
</form>
</div>
your.component.ts:
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
status: [false],
});
// here you put ur async side effect retrieving the data from the
// backend, when you have your data set it to the form
this.form.patchValue({
switch: false,
});
}
CodePudding user response:
It looks like you're using ReactiveForms, here's a good way to do it: 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();
});
}
}