spabloramirez
2/20/2017 - 4:43 PM

Resumen de angular

Resumen de angular

Control styles

ng-pristine/ng-dirty //valor por defecto
ng-touched/ng-untouched
ng-valid/ng-invalid

Forms Template-driven

<input 
    ngModel //Define que un controls de formulario
    name="email" //establece el nombre en form.value.name
    
    [ngModel]="user.name" | controller => view //One way data binding
    ([ngModel])="user.name" | controller <=> view //Two way data binding controller
    
    pattern="regExp"
    required
    #email="ngModel" //local reference
>

Control styles

ng-pristine/ng-dirty //valor por defecto
ng-touched/ng-untouched
ng-valid/ng-invalid

Forms Template-driven

<input 
    ngModel //Define que un controls de formulario
    name="email" //establece el nombre en form.value.name
    
    [ngModel]="user.name" | controller => view //One way data binding
    ([ngModel])="user.name" | controller <=> view //Two way data binding controller
    
    pattern="regExp"
    required
    #email="ngModel" //local reference
>

<form 
    (ngSubmit)="onSubmit(f)" //pasar el formulario al controlador
    #f          //local reference (html)
    #f="ngForm" //local reference (form) 
>
user:{
    name:''    
}

onSubmit(form:ngForm){
    form.value.inputName 
    this.user.name //data binding
}

Anidar datos del form.value

<div ngModelGroup="userData"></div>

Input default value

  user = {    
    gender: 'male'
  };

  genders = [
    'male',
    'female'
  ];   

    <input *ngFor="let g of genders" 
           type="radio"
           name="gender"
           [ngModel]="user.gender" //se asigna el valor por defecto desde controller
           [value]="g" //se establece el valor recibido desde ngModel           
           >
    {{g}}

Forms Data-driven

####asociar formulario y controles

myForm: FormGroup;
this.myForm = formBuilder.group({
    'username': [''],
})
<form [formGroup]="myForm">
<input type="text"
     formControlName="username">
</form>

Validadores

'username': ['ValorDelCampo', 
    [Validators.required,
    Validators.pattern(""),
    this.exampleValidator], 
    this.asyncExampleValidator 
],

 exampleValidator(control: FormControl): {[s: string]: boolean} {
    if (control.value === 'Example') {
      return {example: true};
    }
    return null;
  }

  asyncExampleValidator(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>(
      (resolve, reject) => {
        setTimeout(() => {
          if (control.value === 'Example') {
            resolve({'invalid': true});
          } else {
            resolve(null);
          }
        }, 1500);
      }
    );
    return promise;
  }

comprobar formulario

  <button type="submit" [disabled]="!myForm.valid">Submit</button>

comprobar campos

Invalid Email

Form group

     this.myForm = formBuilder.group({
       'userData': formBuilder.group({
         'username': ['Max', Validators.required],         
       })
     });
     <div *ngIf="!myForm.controls['userData'].controls['email'].valid">
         Invalid Email
       </div>
     
####Radio Button
genders = [
  'male',
  'female'
];
    
'gender': ['male']

<div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio"
              formControlName="gender"
              [value]="g">
      {{g}}
    </label>
  </div>

dinamic inputs

'hobbies': formBuilder.array([
    ['Cooking', Validators.required, this.asyncExampleValidator]
])
onAddHobby() {
    (<FormArray>this.myForm.controls['hobbies']).push(new FormControl('', Validators.required, this.asyncExampleValidator));
}
<div class="form-group"
     *ngFor="let hobby of myForm.controls['hobbies'].controls; let i = index">
  <input type="text"
         class="form-control" formControlName="{{i}}">
</div>

Form observables

this.myForm.statusChanges.subscribe(
  (data: any) => console.log(data)
);
this.myForm.valueChanges.subscribe();

Form reset

this.myForm.reset();
```
Controller

user:{ name:''
}

onSubmit(form:ngForm){ form.value.inputName this.user.name //data binding }


#### Anidar datos del form.value
``` #### Input default value ``` user = { gender: 'male' };

genders = [ 'male', 'female' ];

<input *ngFor="let g of genders" 
       type="radio"
       name="gender"
       [ngModel]="user.gender" //se asigna el valor por defecto desde controller
       [value]="g" //se establece el valor recibido desde ngModel           
       >
{{g}}
 
# Forms Data-driven

####asociar formulario y controles

myForm: FormGroup; this.myForm = formBuilder.group({ 'username': [''], })

``` #### Validadores ``` 'username': ['ValorDelCampo', [Validators.required, Validators.pattern(""), this.exampleValidator], this.asyncExampleValidator ],

exampleValidator(control: FormControl): {[s: string]: boolean} { if (control.value === 'Example') { return {example: true}; } return null; }

asyncExampleValidator(control: FormControl): Promise | Observable { const promise = new Promise( (resolve, reject) => { setTimeout(() => { if (control.value === 'Example') { resolve({'invalid': true}); } else { resolve(null); } }, 1500); } ); return promise; }

#### comprobar formulario
Submit ```

comprobar campos

Invalid Email

Form group

     this.myForm = formBuilder.group({
       'userData': formBuilder.group({
         'username': ['Max', Validators.required],         
       })
     });
     <div *ngIf="!myForm.controls['userData'].controls['email'].valid">
         Invalid Email
       </div>
     
####Radio Button
genders = [
  'male',
  'female'
];
    
'gender': ['male']

<div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio"
              formControlName="gender"
              [value]="g">
      {{g}}
    </label>
  </div>

dinamic inputs

'hobbies': formBuilder.array([
    ['Cooking', Validators.required, this.asyncExampleValidator]
])
onAddHobby() {
    (<FormArray>this.myForm.controls['hobbies']).push(new FormControl('', Validators.required, this.asyncExampleValidator));
}
<div class="form-group"
     *ngFor="let hobby of myForm.controls['hobbies'].controls; let i = index">
  <input type="text"
         class="form-control" formControlName="{{i}}">
</div>

Form observables

this.myForm.statusChanges.subscribe(
  (data: any) => console.log(data)
);
this.myForm.valueChanges.subscribe();

Form reset

this.myForm.reset();