import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {UserService} from '../user.service'; import {User} from '../../core/user'; import {ToasterService} from '../../core/toaster.service'; import {ConfirmDialogComponent} from '../../shared/confirm-dialog/confirm-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import {FormArray, FormBuilder, FormGroup} from '@angular/forms'; @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: '', groups: 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('groups', this.fb.array( item.groups.map( x => this.fb.group({ group: x.enabled }) ) )); } ngAfterViewInit() { setTimeout(() => { this.nameElement.nativeElement.focus(); }, 0); } save() { this.ser.saveOrUpdate(this.getItem()) .subscribe( (result) => { this.toaster.show('Success', ''); this.router.navigateByUrl('/users'); }, (error) => { this.toaster.show('Danger', error.error); } ); } delete() { this.ser.delete(this.item.id) .subscribe( (result) => { this.toaster.show('Success', ''); this.router.navigateByUrl('/users'); }, (error) => { this.toaster.show('Danger', error.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('groups') as FormArray; this.item.groups.forEach((item, index) => { item.enabled = array.controls[index].value.group; }); return this.item; } }