import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, OnInit } from "@angular/core"; import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms"; import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { CfDialog, CheckboxComponent, InputTextComponent, LabelValue, ListboxComponent } from "codefoxui"; import { UserEditor } from "src/app/interfaces"; import { LocalApiService } from "src/app/services/local.api.service"; import { CommonModule } from "@angular/common"; @Component({ standalone: true, selector: 'cf-usereditor', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: 'usereditor.component.html', styleUrls: ['usereditor.component.scss'], imports: [ CommonModule, ReactiveFormsModule, InputTextComponent, CheckboxComponent, ListboxComponent ] }) export class UserEditorComponent extends CfDialog implements OnInit { cdr: ChangeDetectorRef = inject(ChangeDetectorRef); las: LocalApiService = inject(LocalApiService); formGroup: FormGroup = new FormGroup({ username: new FormControl('', [Validators.required]), fullname: new FormControl('', [Validators.required]), email: new FormControl('', [Validators.required, Validators.email]), phone: new FormControl(''), password: new FormControl(''), apiKey: new FormControl(''), active: new FormControl(false), renewApiKey: new FormControl(false), apiEnabled: new FormControl(false), userGroups: new FormControl([]), }); userId: number | null = null; userGroups: LabelValue[] = []; loading: boolean = false; loadUserGroups(): void { this.las.getList('usergroups/list').pipe(takeUntilDestroyed(this.destroyRef)).subscribe((userGroups) => { this.userGroups = userGroups; this.cdr.detectChanges(); }); } get(): void { if (this.userId !== null) { this.las.getUser(this.userId).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(({ userEditor }) => { this.formGroup.patchValue(userEditor); this.cdr.detectChanges(); }); } } save(): void { if (this.loading) { return; } this.loading = true; this.formGroup.disable(); this.cdr.detectChanges(); const userEditor: UserEditor = this.formGroup.value; if (this.userId === null) { this.las.createUser(userEditor).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.close(true); }).add(() => { this.loading = false; this.formGroup.enable(); this.cdr.detectChanges(); }); } else { this.las.updateUser(this.userId, userEditor).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.close(true); }).add(() => { this.loading = false; this.formGroup.enable(); this.cdr.detectChanges(); }); } } ngOnInit(): void { this.cdr.detectChanges(); this.loadUserGroups(); this.get(); } constructor() { super(); this.userId = this.config.getData('userId', null); this.formGroup.valueChanges.pipe(takeUntilDestroyed()).subscribe(() => { this.cdr.detectChanges(); }); this.cdr.detach(); } }