Angular – Reacting

スポンサーリンク

What we want to do

  • Watch to change in form

We want to detect form value change and do something.

Observable

Use the value Changes Observable property
Subscribe to the Observable

Example

Support value change in ReactiveForm

watchformsample.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, AbstractControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './watchformsample.component.html',
  styleUrls: ['./watchformsample.component.css']
})
export class WatchformsampleComponent implements OnInit {

  testForm: FormGroup;

  errorMessage: string;

  constructor(private fb: FormBuilder) { }

  validationMessages = {
    "required": "Nick name is required",
  };

  ngOnInit(): void {

    this.testForm = this.fb.group({
      firstName: ['', [Validators.required, Validators.minLength(3)]],
      lastName: ['', [Validators.required, Validators.maxLength(50)]],
      nickname: ['', [Validators.required]]
    });

    const lastNameControl = this.testForm.get('lastName');
    lastNameControl.valueChanges.subscribe(value => {
        console.log(value);
    });

    this.testForm.valueChanges.subscribe(value => {
        console.log(JSON.stringify(value));
    });

    // Error message
    const nickanmeControl = this.testForm.get('nickname');
    
    nickanmeControl.valueChanges.subscribe(value => {
      console.log(this.testForm.get('nickname').errors);
      this.setMessage(nickanmeControl)
    });
  }

  save() {
    console.log('Saved: ' + JSON.stringify(this.testForm.value));
  }

  setMessage(c: AbstractControl) {
    if ((c.touched || c.dirty) && c.errors) {
      this.errorMessage = Object.keys(c.errors).map(
       key => this.validationMessages[key]).join(' ');
    }
    console.log(this.errorMessage);
  }
}

Get control and call valueChanges

To subscribe and callback to handle, can detect value change

watchformsample.component.html

<h2>Home Builder Validation</h2>
<form (ngSubmit)="save()" [formGroup]="testForm">
    <input id="firstNameId" type="text"
        placeholder=""
        formControlName="firstName"
        [ngClass]="{'is-valid': (testForm.get('firstName').touched || testForm.get('firstName').dirty)
                &amp;&amp; !testForm.get('firstName').valid }"/>
    <br>

    <span class="invalid-feedback">
        <span *ngIf="testForm.get('firstName').errors?.required">
        Please enter your first name.
        </span>
        <span *ngIf="testForm.get('firstName').errors?.minlength">
        The first name must be longer than 3 characters.
        </span>
    </span>
    <br>
    <br>

    <input id="lastNameId" type="text"
        placeholder=""
        formControlName="lastName"
        [ngClass]="{'is-valid': (testForm.get('lastName').touched || testForm.get('lastName').dirty)
        &amp;&amp; !testForm.get('lastName').valid }"/>
    <br>

    <span class="invalid-feedback">
        <span *ngIf="testForm.get('lastName').errors?.required">
          Please enter your last name.
        </span>
        <span *ngIf="testForm.get('lastName').errors?.maxlength">
          The last name must be less than 50 characters.
        </span>
    </span>
    <br>

    <input id="nicknameId" type="text"
    placeholder=""
    formControlName="nickname"
    [ngClass]="{'is-valid': (testForm.get('nickname').touched || testForm.get('nickname').dirty)
        &amp;&amp; !testForm.get('nickname').valid }"/>
    <br>

    <div class="invalid-feedback" *ngIf="testForm.get('nickname').errors?.required">
     <span>{{errorMessage}}</span>
    </div>


    <button class="btn btn-primary mr-3"
        type="submit"
        style="width:80px"
        [disabled]="!testForm.valid">Save</button>        
</form>

Reacting Transformations

Pipe event

NameDescription
debounceTimeIgnore events until a specific time has passed
without another event
One event -> wait
throttleTimeEmits a value, then ignores subsequent values for
a specific amount of time
Only total (start event)

Example

nickanmeControl.valueChanges.pipe(
      debounceTime(1000)  // 1000ms -> 1s
    ).subscribe(value =>
      this.setMessage(nickanmeControl)
    );
// throttleTime(1000)
未分類
スポンサーリンク
Professional Programmer2

コメント