Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Input, ViewChild } from '@angular/core';
- import {
- AbstractControl,
- AsyncValidatorFn,
- FormBuilder,
- FormControl,
- FormGroup,
- NgForm,
- ValidationErrors,
- Validators
- } from '@angular/forms';
- import { combineLatest, fromEvent, interval, Observable, of, timer } from 'rxjs';
- import { catchError, debounce, debounceTime, delay, distinct, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
- import { HttpClient } from '@angular/common/http';
- import { Meteo } from './model/meteo';
- import { environment } from '../environments/environment';
- @Component({
- selector: 'biz-root',
- template: `
- <form [formGroup]="form" (ngSubmit)="save()">
- {{form.get('city').valid}}
- {{form.get('city').touched}}
- {{form.get('city').dirty}}
- {{form.get('city').errors | json}}
- {{form.get('city').pending}}
- <br>
- <input type="text" formControlName="city" >
- <input type="text" formControlName="unit" >
- <input type="checkbox" formControlName="isCompany"> isCompany?
- <h1>
- <i class="fa fa-check" *ngIf="form.get('userInfo').valid"></i>
- anagrafica</h1>
- <button [disabled]="form.invalid || form.pending">SEND</button>
- <div *ngIf="form.get('userInfo').valid">
- STEP 2
- </div>
- </form>
- <pre>{{data | json}}</pre>
- `,
- styles: []
- })
- export class AppComponent implements AfterViewInit {
- form: FormGroup;
- data: Meteo;
- constructor(private http: HttpClient, private fb: FormBuilder) {
- this.form = fb.group({
- city: [
- '',
- Validators.compose([Validators.required, Validators.minLength(3), c => alphaNumeric(c, 4)]),
- this.uniqueName()
- ],
- isCompany: true,
- unit: ['metric', Validators.required],
- userInfo: fb.group({
- name: ['', Validators.required],
- surname: ''
- })
- })
- this.form.get('isCompany').valueChanges
- .subscribe(isCompany => {
- if (isCompany) {
- this.form.get('userInfo').get('name').setValidators(Validators.required)
- // this.form.get('userInfo').disable();
- } else {
- this.form.get('userInfo').get('name').setValidators([])
- // this.form.get('userInfo').enable();
- }
- this.form.get('userInfo').get('name').updateValueAndValidity();
- })
- const fakeServerUser = {
- city: 'aaa',
- isCompany: true,
- userInfo: {
- name: 'Fab',
- surname: 'Bio'
- }
- }
- this.form.patchValue(fakeServerUser)
- /*
- this.form.valueChanges
- .pipe(
- debounceTime(1000),
- switchMap(
- formData => this.http.get<Meteo>(`http://api.openweathermap.org/data/2.5\/weather?q=${formData.city}&units=${formData.unit}&APPID=eb03b1f5e5afb5f4a4edb40c1ef2f534`)
- .pipe(
- delay(environment.production ? 0 : 1000),
- catchError(err => {
- return of(null);
- })
- )
- )
- )
- .subscribe(
- data => {
- this.data = data;
- },
- err => alert('error')
- )
- */
- }
- // ---o---o----xo-------->
- ngAfterViewInit(): void {
- }
- save(): void {
- console.log(this.form.value)
- // console.log(this.username.nativeElement.value)
- }
- URL = 'https://jsonplaceholder.typicode.com';
- uniqueName(): AsyncValidatorFn {
- return (control: FormControl): Observable<{ [key: string]: any } | null> => {
- return timer(1000)
- .pipe(
- switchMap(() => this.http.get<any>(`${this.URL}/users?username=${control.value}`)),
- map(res => res.length ? { notAvailable: true } : null)
- );
- };
- }
- }
- const ALPHA_NUMERIC_REGEX = /^([A-Za-z]|[0-9]|_)+$/;
- function alphaNumeric(c: AbstractControl, totalLenght: number): ValidationErrors | null {
- if (c.value.length !== totalLenght) {
- return { notEqual: true}
- }
- if (c.value && !c.value.match(ALPHA_NUMERIC_REGEX)){
- return { alphaNumeric: true };
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement