Advertisement
Guest User

Untitled

a guest
May 15th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.30 KB | None | 0 0
  1. import { Component, OnInit, Inject, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
  2. import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
  3. import { FormBuilder, Validators, FormGroup } from '@angular/forms';
  4. import { FileUploader, FileLikeObject } from 'ng2-file-upload';
  5. import { AppSettings } from 'app/shared/app.settings';
  6. import { CustomValidators } from 'app/shared/validators/CustomValidators';
  7. import { User } from 'app/shared/models/user';
  8. import { Group } from 'app/shared/models/group';
  9. import { AuthService } from 'app/shared/services/auth.service';
  10.  
  11. @Component({
  12. selector: 'app-ngx-table-popup',
  13. templateUrl: './ngx-table-popup.component.html',
  14. // changeDetection: ChangeDetectionStrategy.OnPush,
  15. })
  16. export class NgxTablePopupComponent implements OnInit {
  17. public rForm: FormGroup;
  18. public profile: User;
  19. public avatar: string;
  20. public groups: Group[];
  21. public isNew: boolean;
  22. public status: string;
  23. public rol: string;
  24. public roles: { value: string; text: string }[];
  25. public hasBaseDropZoneOver;
  26. public showPassword: string;
  27. public uploaderConfiguration = {
  28. allowedMimeType: ['image/jpeg', 'image/png'],
  29. maxFileSize: 0.5 * 1024 * 1024,
  30. errorMessage: '',
  31. };
  32. public uploader: FileUploader = new FileUploader({
  33. autoUpload: false,
  34. allowedMimeType: this.uploaderConfiguration.allowedMimeType,
  35. maxFileSize: this.uploaderConfiguration.maxFileSize,
  36. url: AppSettings.API_ENDPOINT_USER_UPLOAD_AVATAR,
  37. });
  38. constructor(
  39. @Inject(MAT_DIALOG_DATA) public data: any,
  40. public dialogRef: MatDialogRef<NgxTablePopupComponent>,
  41. private cd: ChangeDetectorRef,
  42. private fb: FormBuilder,
  43. private authService: AuthService,
  44. ) {}
  45.  
  46. ngOnInit() {
  47. this.groups = this.data.payload.groups;
  48. this.isNew = this.data.payload.isNew;
  49. this.status = this.data.payload.status;
  50. this.rol = this.data.payload.rol;
  51. this.roles = AppSettings.ROLES;
  52. this.profile = this.data || {};
  53. if (!this.isNew) {
  54. this.data.payload.user.subscribe(data => {
  55. this.profile = data;
  56. this.avatar = data.avatar;
  57. });
  58. }
  59.  
  60. this.buildItemForm(this.profile);
  61. }
  62. buildItemForm(item) {
  63. const passwords = this.isNew
  64. ? this.fb.group(
  65. {
  66. password: [
  67. '',
  68. Validators.compose([
  69. Validators.required,
  70. Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/),
  71. ]),
  72. ],
  73. confirm_password: [
  74. '',
  75. Validators.compose([
  76. Validators.required,
  77. Validators.pattern(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/),
  78. ]),
  79. ],
  80. },
  81. {
  82. validator: CustomValidators.Match('password', 'confirm_password'),
  83. updateOn: 'blur',
  84. },
  85. )
  86. : this.fb.group({
  87. password: [],
  88. confirm_password: [],
  89. });
  90. this.rForm = this.fb.group(
  91. {
  92. passwords,
  93. username: item.username,
  94. avatar: item.avatar,
  95. name: [item.name, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
  96. surname: [item.surname, Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Zá-ú\s]{3,50}$/)])],
  97. rol: [{ value: this.rol, disabled: true }],
  98. email: [item.email, Validators.compose([Validators.required, Validators.email])],
  99. group: item.group,
  100. confirm: item.confirm || false,
  101. },
  102. {
  103. updateOn: 'blur',
  104. },
  105. );
  106. this.onChangeEmail();
  107. this.onChangeUsername();
  108. this.uploader.onWhenAddingFileFailed = (item, filter, options) =>
  109. this.onWhenAddingFileFailed(item, filter, options);
  110.  
  111. this.uploader.onBeforeUploadItem = item => (item.withCredentials = false);
  112.  
  113. this.uploader.onAfterAddingFile = item => {
  114. const fileReader = new FileReader();
  115. fileReader.onloadend = e => {
  116. const imageData = fileReader.result;
  117. this.avatar = imageData.split('base64,')[1];
  118. this.uploaderConfiguration = {
  119. ...this.uploaderConfiguration,
  120. errorMessage: '',
  121. };
  122. this.cd.detectChanges();
  123. };
  124. fileReader.readAsDataURL(item._file);
  125. };
  126. }
  127.  
  128. private onWhenAddingFileFailed(item: FileLikeObject, filter: any, options: any) {
  129. const allowedTypes = this.uploaderConfiguration.allowedMimeType.join();
  130. const imageSize = Math.round(item.size / 1024);
  131. const errors = {
  132. fileSize: `Tamaño máximo de la imagen excedido (${imageSize} Bytes de ${this.uploaderConfiguration.maxFileSize /
  133. 1024} Bytes permitidos)`,
  134. mimeType: `Formato: "${item.type} no es permitido. Formatos permitidos: "${allowedTypes}"`,
  135. };
  136. const errorMessage = errors[filter.name] || `Error desconocido: ${filter.name}`;
  137. this.uploaderConfiguration = {
  138. ...this.uploaderConfiguration,
  139. errorMessage,
  140. };
  141. }
  142.  
  143. private onChangeUsername(): void {
  144. this.rForm.get('username').valueChanges.subscribe((username: string) => {
  145. if (username.length < 6) {
  146. return;
  147. }
  148. this.authService.isUsernameBusy(username).subscribe(isBusy => {
  149. if (isBusy) {
  150. this.rForm.controls.username.setErrors({ isBusy });
  151. }
  152. });
  153. });
  154. }
  155. private onChangeEmail(): void {
  156. this.rForm.get('email').valueChanges.subscribe((email: string) => {
  157. if (email.length < 3) {
  158. return;
  159. }
  160. this.authService.isEmailBusy(email).subscribe(isBusy => {
  161. if (isBusy) {
  162. this.rForm.controls.email.setErrors({ isBusy });
  163. }
  164. });
  165. });
  166. }
  167.  
  168. private hasFieldInForm(user: User, field: string) {
  169. if (this.rForm.value[field]) {
  170. user[field] = this.rForm.value[field];
  171. }
  172. }
  173. public fileOverBase(e: any): void {
  174. this.hasBaseDropZoneOver = e;
  175. }
  176.  
  177. public hasError(formField: string, validators: string[]): boolean {
  178. return (
  179. this.rForm.controls[formField].touched &&
  180. validators.some(validator => this.rForm.controls[formField].hasError(validator))
  181. );
  182. }
  183. hasErrorPassword(formField: string, validators: string[]): boolean {
  184. const control = (this.rForm.controls['passwords'] as FormGroup).controls.password;
  185. return control.touched && validators.some(validator => control.hasError(validator));
  186. }
  187. public changeShowPassword() {
  188. this.showPassword = this.showPassword === 'password' ? 'text' : 'password';
  189. }
  190. public isVisiblePassword() {
  191. return this.showPassword === 'text';
  192. }
  193.  
  194. public isTeacher() {
  195. return this.rol === 'teacher';
  196. }
  197.  
  198. public isStudent() {
  199. return this.rol === 'user';
  200. }
  201. submit() {
  202. const user: User = new User({
  203. username: this.rForm.get('username').value,
  204. name: this.rForm.get('name').value,
  205. surname: this.rForm.get('surname').value,
  206. email: this.rForm.get('email').value,
  207. avatar: this.avatar,
  208. group: this.rForm.get('group').value,
  209. password: this.rForm.get('passwords').get('password').value,
  210. rol: this.rForm.get('rol').value,
  211. confirm: this.rForm.get('confirm').value,
  212. status: this.status,
  213. });
  214. this.dialogRef.close(user);
  215. }
  216. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement