Web Developer

Section 15 Form – Reactive Angular form

  1. In ts file, declare a property for the form, which type should be FormGroup: such as: signupForm: FormGroup;
  2. Initiate the form in ngOnInit() method:
    1. signupForm = new FormGroup({
      1. propertyName1: new FormControl(defaultName, validator, validator),
      2. propertyName2: new FormControl(defaultName, Validators.required / [Validators.required, Validators.email, …], validator),
      3. …});
  3. synchronize the form you create with the form in template
    1. binding the created form to template form in <form> tag with formGroup directive, such as: <form [formGroup] = “signupFom”> … </form>
    2. sign each form control you create to template form control with formControlName directive, such as: <input … formControlName = “propertyName1” …>
  4. To access each form control object, using get(propertyName), such as:
    1. signupForm.get(‘username’).valid
    2. signupForm.get(‘username’).touched
    3. signupForm.valid // get the whole form validation
  5. FormArray is an array holding a set of form controls, can be used to add new controls form to the form by user.
  6. create your own validators, validator just a function, you need to create a function, return {errorName: boolean}, then put it to form registration part, the second argument:
    1. nameForbidden(control: FormControl): {[s: string]: boolean} {
      1. if (ArrayIncludeNameIdFobidden.indexOf(control.value) !== -1) {return {“nameIsForbidden”: true}}
      2. return null;
    2. }
  7. create your own asynchronous validator, most same as #6 step, however, return is Promise<any> | Observable<any>, and put it to third argument
  8. valueChanges & statusChanges: two observables using to monitor the form changes.
  9. setValue and patchValue: two methods to be used for set the default value of the form

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>