I am working on angular and am stuck for a while .. Help much needed. Thanks in advance for your time.
With Ref to : binding data to angular checkbox
I have created my code .. but am stuck to bind the check value from API call .. Kindly help
---------TS CODE---------
import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormArray, FormControl } from '@angular/forms';
import { JsonService } from '../../../services/json.service';
import { UserService } from '../../../services/user.service';
import { Router } from '@angular/router'
import { of } from 'rxjs';
export class InterestComponent implements OnInit {
interestList = [];
message;
messageClass;
processing = false;
form: FormGroup;
interests = [];
getUserInterest() {
this.jsonService.getInterest().
subscribe(
interest => {
this.interests = interest.interests;
console.log('Interest:', this.interests);
}
)
}
constructor(
private formBuilder: FormBuilder,
private router: Router,
private jsonService: JsonService,
private userService: UserService,
) {
this.form = this.formBuilder.group({
interestList: this.formBuilder.array([]),
});
this.interests.map(x => this.interestList.indexOf(x.value) >= 0 ? x.checked = true : x.checked = false)
this.interestList.map((x) => this.ssArray.push(this.formBuilder.control(x)))
}
get ssArray() {
return this.form.get('interestList') as FormArray;
}
onCheckChange(event) {
if (event.target.checked) {
this.ssArray.push(this.formBuilder.control(event.target.value));
}
else {
this.ssArray.removeAt(this.ssArray.value.findIndex(x => x === event.target.value))
}
}
getAllInterest() {
this.userService.getInterest().subscribe((data: any) => {
this.interestList = data.interest;
console.log(this.interestList)
});
}
onInterestSubmit() {
const interest = {
interestList: this.form.get('interestList').value as FormArray,
}
//submit code --working
}
ngOnInit(): void {
this.getUserInterest();
this.getAllInterest();
}
}
-----------HTML CODE ------
<div *ngFor="let interest of interests; let i = index;">
<div class="interest-box">
<input type="checkbox" id="" class="chk" [value]="interest.value" [checked]="interest.checked" (change)="onCheckChange($event)">
<label class="image-checkbox" for="">
</label>
</div>
</div>
---my json---
{ "interests": [{"name": "Acting","value": "acting", "checked": false },
{"name": "Adventure","value": "adventure","checked": false },
{"name": "Agriculture", "value": "agriculture","checked": false}]}
Aucun commentaire:
Enregistrer un commentaire