import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormArray, FormBuilder, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Router } from '@angular/router'; import { ToasterService } from '../../core/toaster.service'; import { User } from '../../core/user'; import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component'; import { UserService } from '../user.service'; @Component({ selector: 'app-user-detail', templateUrl: './user-detail.component.html', styleUrls: ['./user-detail.component.css'], }) export class UserDetailComponent implements OnInit, AfterViewInit { @ViewChild('nameElement', { static: true }) nameElement: ElementRef; form: FormGroup; item: User; hide: boolean; constructor( private route: ActivatedRoute, private router: Router, private fb: FormBuilder, private toaster: ToasterService, private dialog: MatDialog, private ser: UserService, ) { this.hide = true; this.createForm(); } createForm() { this.form = this.fb.group({ name: '', password: '', lockedOut: '', roles: this.fb.array([]), }); } ngOnInit() { this.route.data.subscribe((data: { item: User }) => { this.showItem(data.item); }); } showItem(item: User) { this.item = item; this.form.get('name').setValue(item.name); this.form.get('password').setValue(''); this.form.get('lockedOut').setValue(item.lockedOut); this.form.setControl( 'roles', this.fb.array( item.roles.map((x) => this.fb.group({ role: x.enabled, }), ), ), ); } ngAfterViewInit() { setTimeout(() => { this.nameElement.nativeElement.focus(); }, 0); } save() { if (this.route.snapshot.paramMap.get('id') === 'me') { this.ser.updateMe(this.getItem()).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/'); }, (error) => { this.toaster.show('Danger', error); }, ); } else { this.ser.saveOrUpdate(this.getItem()).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/users'); }, (error) => { this.toaster.show('Danger', error); }, ); } } delete() { this.ser.delete(this.item.id).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/users'); }, (error) => { this.toaster.show('Danger', error); }, ); } confirmDelete(): void { const dialogRef = this.dialog.open(ConfirmDialogComponent, { width: '250px', data: { title: 'Delete User?', content: 'Are you sure? This cannot be undone.' }, }); dialogRef.afterClosed().subscribe((result: boolean) => { if (result) { this.delete(); } }); } getItem(): User { const formModel = this.form.value; this.item.name = formModel.name; this.item.password = formModel.password; this.item.lockedOut = formModel.lockedOut; const array = this.form.get('roles') as FormArray; this.item.roles.forEach((item, index) => { item.enabled = array.controls[index].value.role; }); return this.item; } }