Advertisement
fabiobiondi

Untitled

May 21st, 2021
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.12 KB | None | 0 0
  1. import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Input, ViewChild } from '@angular/core';
  2. import {
  3. AbstractControl,
  4. AsyncValidatorFn,
  5. FormBuilder,
  6. FormControl,
  7. FormGroup,
  8. NgForm,
  9. ValidationErrors,
  10. Validators
  11. } from '@angular/forms';
  12. import { combineLatest, fromEvent, interval, Observable, of, timer } from 'rxjs';
  13. import { catchError, debounce, debounceTime, delay, distinct, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
  14. import { HttpClient } from '@angular/common/http';
  15. import { Meteo } from './model/meteo';
  16. import { environment } from '../environments/environment';
  17.  
  18. @Component({
  19. selector: 'biz-root',
  20. template: `
  21. <form [formGroup]="form" (ngSubmit)="save()">
  22. {{form.get('city').valid}}
  23. {{form.get('city').touched}}
  24. {{form.get('city').dirty}}
  25. {{form.get('city').errors | json}}
  26. {{form.get('city').pending}}
  27.  
  28. <br>
  29. <input type="text" formControlName="city" >
  30. <input type="text" formControlName="unit" >
  31. <input type="checkbox" formControlName="isCompany"> isCompany?
  32. <h1>
  33. <i class="fa fa-check" *ngIf="form.get('userInfo').valid"></i>
  34. anagrafica</h1>
  35.  
  36. <button [disabled]="form.invalid || form.pending">SEND</button>
  37.  
  38. <div *ngIf="form.get('userInfo').valid">
  39. STEP 2
  40. </div>
  41. </form>
  42.  
  43. <pre>{{data | json}}</pre>
  44. `,
  45. styles: []
  46. })
  47. export class AppComponent implements AfterViewInit {
  48.  
  49. form: FormGroup;
  50.  
  51. data: Meteo;
  52.  
  53. constructor(private http: HttpClient, private fb: FormBuilder) {
  54. this.form = fb.group({
  55. city: [
  56. '',
  57. Validators.compose([Validators.required, Validators.minLength(3), c => alphaNumeric(c, 4)]),
  58. this.uniqueName()
  59. ],
  60. isCompany: true,
  61. unit: ['metric', Validators.required],
  62. userInfo: fb.group({
  63. name: ['', Validators.required],
  64. surname: ''
  65. })
  66. })
  67.  
  68. this.form.get('isCompany').valueChanges
  69. .subscribe(isCompany => {
  70. if (isCompany) {
  71. this.form.get('userInfo').get('name').setValidators(Validators.required)
  72. // this.form.get('userInfo').disable();
  73. } else {
  74. this.form.get('userInfo').get('name').setValidators([])
  75. // this.form.get('userInfo').enable();
  76. }
  77. this.form.get('userInfo').get('name').updateValueAndValidity();
  78. })
  79.  
  80.  
  81. const fakeServerUser = {
  82. city: 'aaa',
  83. isCompany: true,
  84. userInfo: {
  85. name: 'Fab',
  86. surname: 'Bio'
  87. }
  88. }
  89. this.form.patchValue(fakeServerUser)
  90. /*
  91.  
  92. this.form.valueChanges
  93. .pipe(
  94. debounceTime(1000),
  95. switchMap(
  96. formData => this.http.get<Meteo>(`http://api.openweathermap.org/data/2.5\/weather?q=${formData.city}&units=${formData.unit}&APPID=eb03b1f5e5afb5f4a4edb40c1ef2f534`)
  97. .pipe(
  98. delay(environment.production ? 0 : 1000),
  99. catchError(err => {
  100. return of(null);
  101. })
  102. )
  103. )
  104. )
  105. .subscribe(
  106. data => {
  107. this.data = data;
  108. },
  109. err => alert('error')
  110. )
  111. */
  112.  
  113.  
  114.  
  115. }
  116.  
  117. // ---o---o----xo-------->
  118. ngAfterViewInit(): void {
  119.  
  120. }
  121.  
  122. save(): void {
  123. console.log(this.form.value)
  124. // console.log(this.username.nativeElement.value)
  125. }
  126.  
  127. URL = 'https://jsonplaceholder.typicode.com';
  128.  
  129. uniqueName(): AsyncValidatorFn {
  130. return (control: FormControl): Observable<{ [key: string]: any } | null> => {
  131. return timer(1000)
  132. .pipe(
  133. switchMap(() => this.http.get<any>(`${this.URL}/users?username=${control.value}`)),
  134. map(res => res.length ? { notAvailable: true } : null)
  135. );
  136. };
  137. }
  138. }
  139.  
  140. const ALPHA_NUMERIC_REGEX = /^([A-Za-z]|[0-9]|_)+$/;
  141.  
  142. function alphaNumeric(c: AbstractControl, totalLenght: number): ValidationErrors | null {
  143. if (c.value.length !== totalLenght) {
  144. return { notEqual: true}
  145. }
  146. if (c.value && !c.value.match(ALPHA_NUMERIC_REGEX)){
  147. return { alphaNumeric: true };
  148. }
  149. return null;
  150. }
  151.  
  152.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement