import { DataSource } from '@angular/cdk/table'; import { BehaviorSubject, Observable, merge } from 'rxjs'; import { map } from 'rxjs/operators'; import { CollectionViewer } from '@angular/cdk/collections'; import { BankAccounts } from 'src/modules/sites/model/bank-accounts.model'; import { BankAccountsService } from 'src/modules/sites/service/bank-accounts.service'; import { FormControl, FormGroup, Validators, FormArray } from '@angular/forms'; export class BankAccountsListDataSource extends DataSource { private _objectStore: BankAccounts[] = []; private _ObjectsSubject$ = new BehaviorSubject([]); private _loadingSubject$ = new BehaviorSubject(false); public loading$ = this._loadingSubject$.asObservable(); public formg: FormGroup; constructor(private bankAccountsService: BankAccountsService) { super(); } connect(collectionViewer: CollectionViewer): Observable { return this.bankAccountsService.getAllAsFormArray().pipe( map(res => { res.forEach(m => this._objectStore.push(m as BankAccounts)); this._ObjectsSubject$.next(this._objectStore); let fa = this.formg.get('formarray'); res.forEach(r => fa.push(this.createRowFormGroup(r))); return res; }) ); } createRowFormGroup(r: BankAccounts): FormGroup { let f = new FormGroup({ id: this.createNewFormContorl(r, 'id'), name: this.createNewFormContorl(r, 'name'), number: this.createNewFormContorl(r, 'number'), holder: this.createNewFormContorl(r, 'holder'), description: this.createNewFormContorl(r, 'description') }); return f; } createNewFormContorl(r: BankAccounts, propName: string): FormControl { let m = new FormControl(r[propName], Validators.required); m.valueChanges.subscribe(val => { r[propName] = val; }); return m; } disconnect(collectionViewer: CollectionViewer): void { this._ObjectsSubject$.complete(); this._loadingSubject$.complete(); } }