Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, Inject, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
- import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
- import { FormBuilder, Validators, FormGroup } from '@angular/forms';
- import { FileUploader, FileLikeObject } from 'ng2-file-upload';
- import { AppSettings } from 'app/shared/app.settings';
- import { CustomValidators } from 'app/shared/validators/CustomValidators';
- import { User } from 'app/shared/models/user';
- import { Group } from 'app/shared/models/group';
- import { AuthService } from 'app/shared/services/auth.service';
- @Component({
- selector: 'app-ngx-table-popup',
- templateUrl: './ngx-table-popup.component.html',
- // changeDetection: ChangeDetectionStrategy.OnPush,
- })
- export class NgxTablePopupComponent implements OnInit {
- public rForm: FormGroup;
- public profile: User;
- public avatar: string;
- public groups: Group[];
- public isNew: boolean;
- public status: string;
- public rol: string;
- public roles: { value: string; text: string }[];
- public hasBaseDropZoneOver;
- public showPassword: string;
- public uploaderConfiguration = {
- allowedMimeType: ['image/jpeg', 'image/png'],
- maxFileSize: 0.5 * 1024 * 1024,
- errorMessage: '',
- };
- public uploader: FileUploader = new FileUploader({
- autoUpload: false,
- allowedMimeType: this.uploaderConfiguration.allowedMimeType,
- maxFileSize: this.uploaderConfiguration.maxFileSize,
- url: AppSettings.API_ENDPOINT_USER_UPLOAD_AVATAR,
- });
- constructor(
- @Inject(MAT_DIALOG_DATA) public data: any,
- public dialogRef: MatDialogRef<NgxTablePopupComponent>,
- private cd: ChangeDetectorRef,
- private fb: FormBuilder,
- private authService: AuthService,
- ) {}
- ngOnInit() {
- this.groups = this.data.payload.groups;
- this.isNew = this.data.payload.isNew;
- this.status = this.data.payload.status;
- this.rol = this.data.payload.rol;
- this.roles = AppSettings.ROLES;
- this.profile = this.data || {};
- if (!this.isNew) {
- this.data.payload.user.subscribe(data => {
- this.profile = data;
- this.avatar = data.avatar;
- });
- }
- this.buildItemForm(this.profile);
- }
- buildItemForm(item) {
- const passwords = this.isNew
- ? this.fb.group(
- {
- password: [
- '',
- Validators.compose([
- Validators.required,
- Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/),
- ]),
- ],
- confirm_password: [
- '',
- Validators.compose([
- Validators.required,
- Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/),
- ]),
- ],
- },
- {
- validator: CustomValidators.Match('password', 'confirm_password'),
- updateOn: 'blur',
- },
- )
- : this.fb.group({
- password: [],
- confirm_password: [],
- });
- this.rForm = this.fb.group(
- {
- passwords,
- username: item.username,
- avatar: item.avatar,
- name: [item.name, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
- surname: [item.surname, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
- rol: [{ value: this.rol, disabled: true }],
- email: [item.email, Validators.compose([Validators.required, Validators.email])],
- group: item.group,
- confirm: item.confirm || false,
- },
- {
- updateOn: 'blur',
- },
- );
- this.onChangeEmail();
- this.onChangeUsername();
- this.uploader.onWhenAddingFileFailed = (item, filter, options) =>
- this.onWhenAddingFileFailed(item, filter, options);
- this.uploader.onBeforeUploadItem = item => (item.withCredentials = false);
- this.uploader.onAfterAddingFile = item => {
- const fileReader = new FileReader();
- fileReader.onloadend = e => {
- const imageData = fileReader.result;
- this.avatar = imageData.split('base64,')[1];
- this.uploaderConfiguration = {
- ...this.uploaderConfiguration,
- errorMessage: '',
- };
- this.cd.detectChanges();
- };
- fileReader.readAsDataURL(item._file);
- };
- }
- private onWhenAddingFileFailed(item: FileLikeObject, filter: any, options: any) {
- const allowedTypes = this.uploaderConfiguration.allowedMimeType.join();
- const imageSize = Math.round(item.size / 1024);
- const errors = {
- fileSize: `Tamaño máximo de la imagen excedido (${imageSize} Bytes de ${this.uploaderConfiguration.maxFileSize /
- 1024} Bytes permitidos)`,
- mimeType: `Formato: "${item.type} no es permitido. Formatos permitidos: "${allowedTypes}"`,
- };
- const errorMessage = errors[filter.name] || `Error desconocido: ${filter.name}`;
- this.uploaderConfiguration = {
- ...this.uploaderConfiguration,
- errorMessage,
- };
- }
- private onChangeUsername(): void {
- this.rForm.get('username').valueChanges.subscribe((username: string) => {
- if (username.length < 6) {
- return;
- }
- this.authService.isUsernameBusy(username).subscribe(isBusy => {
- if (isBusy) {
- this.rForm.controls.username.setErrors({ isBusy });
- }
- });
- });
- }
- private onChangeEmail(): void {
- this.rForm.get('email').valueChanges.subscribe((email: string) => {
- if (email.length < 3) {
- return;
- }
- this.authService.isEmailBusy(email).subscribe(isBusy => {
- if (isBusy) {
- this.rForm.controls.email.setErrors({ isBusy });
- }
- });
- });
- }
- private hasFieldInForm(user: User, field: string) {
- if (this.rForm.value[field]) {
- user[field] = this.rForm.value[field];
- }
- }
- public fileOverBase(e: any): void {
- this.hasBaseDropZoneOver = e;
- }
- public hasError(formField: string, validators: string[]): boolean {
- return (
- this.rForm.controls[formField].touched &&
- validators.some(validator => this.rForm.controls[formField].hasError(validator))
- );
- }
- hasErrorPassword(formField: string, validators: string[]): boolean {
- const control = (this.rForm.controls['passwords'] as FormGroup).controls.password;
- return control.touched && validators.some(validator => control.hasError(validator));
- }
- public changeShowPassword() {
- this.showPassword = this.showPassword === 'password' ? 'text' : 'password';
- }
- public isVisiblePassword() {
- return this.showPassword === 'text';
- }
- public isTeacher() {
- return this.rol === 'teacher';
- }
- public isStudent() {
- return this.rol === 'user';
- }
- submit() {
- const user: User = new User({
- username: this.rForm.get('username').value,
- name: this.rForm.get('name').value,
- surname: this.rForm.get('surname').value,
- email: this.rForm.get('email').value,
- avatar: this.avatar,
- group: this.rForm.get('group').value,
- password: this.rForm.get('passwords').get('password').value,
- rol: this.rForm.get('rol').value,
- confirm: this.rForm.get('confirm').value,
- status: this.status,
- });
- this.dialogRef.close(user);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement