import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, OnInit } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { ButtonDirective, CfDialog, InputTextComponent, TreeComponent } from 'codefoxui'; import { Permission, UserGroupEditor } from 'src/app/interfaces'; import { LocalApiService } from 'src/app/services/local.api.service'; @Component({ standalone: true, selector: 'app-usergroupeditor', templateUrl: './usergroupeditor.component.html', styleUrls: ['./usergroupeditor.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, imports: [ CommonModule, ReactiveFormsModule, InputTextComponent, TreeComponent, ButtonDirective ] }) export class UsergroupeditorComponent extends CfDialog implements OnInit { las: LocalApiService = inject(LocalApiService); cdr: ChangeDetectorRef = inject(ChangeDetectorRef); userGroupId: number | null = null; formGroup: FormGroup = new FormGroup({ name: new FormControl('', [Validators.required]), permissions: new FormControl([]) }); permissions: Permission[] = []; loading: boolean = false; getPermission(): void { this.las.getPermissions().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(({ permissions }) => { this.permissions = permissions; this.cdr.detectChanges(); }); } get(): void { if (this.userGroupId !== null) { this.las.getUserGroup(this.userGroupId).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(({ userGroupEditor }) => { this.formGroup.patchValue(userGroupEditor, {emitEvent: false}); this.cdr.detectChanges(); }); } } save(): void { if (this.loading) { return; } this.loading = true; this.formGroup.disable(); this.cdr.detectChanges(); const userGroupEditor: UserGroupEditor = this.formGroup.value; if (this.userGroupId === null) { this.las.createUserGroup(userGroupEditor).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.close(true); }).add(() => { this.loading = false; this.formGroup.enable(); this.cdr.detectChanges(); }); } else { this.las.updateUserGroup(this.userGroupId, userGroupEditor).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.close(true); }).add(() => { this.loading = false; this.formGroup.enable(); this.cdr.detectChanges(); }); } } ngOnInit(): void { this.cdr.detectChanges(); this.getPermission(); this.get(); } constructor() { super(); this.userGroupId = this.config.getData('userGroupId'); this.formGroup.valueChanges.pipe(takeUntilDestroyed()).subscribe(() => { this.cdr.detectChanges(); }); this.cdr.detach(); } }