如何检查角度4/6中的状态变化?

时间:2018-12-27 10:16:27

标签: javascript angular typescript

我的任务是创建一个帐户信息网页,该网页包含4个预填字段(给定名称,姓氏,用户名和电子邮件),并在底部设有一个公共保存按钮。用户可以通过相应字段更改任何字段。我希望仅当用户更改任何字段时才启用保存按钮。有跟踪状态变化的方法吗?我的代码如下:

 <mat-card-content>
    <div class="form-group">
      <mat-form-field class="simple-form-field-50">
        <input matInput placeholder="Given name" name="givenName" formControlName="givenName">
      </mat-form-field>
      <mat-form-field class="simple-form-field-50">
        <input matInput placeholder="Family name" name="familyName" formControlName="familyName">
      </mat-form-field>
      <br>
      <mat-form-field>
        <input matInput placeholder="Email" name="email" formControlName="email">
      </mat-form-field>
      <br>
      <button
          [disabled]="waiting"
          class="simple-form-button" 
          color="primary" 
          mat-raised-button 
          type="submit" 
          value="submit">
        Save
      </button> 
    </div>
</mat-card-content>

我的代码输出: Code Output

4 个答案:

答案 0 :(得分:3)

由于您使用的是反应式表单,因此可以在FormGroup上使用valueChanges

由于它的类型为Observable,因此您可以subscribe为其设置一个类型为boolean的变量,该变量将在模板中用于启用按钮。

...

@Component({...})
export class AppComponent  {
  form: FormGroup;
  disableButton = true;

  ngOnInit() {
    ...

    this.form.valueChanges.subscribe(changes => this.disableButton = false);

  }
}

在您的模板中:

<form [formGroup]="form">
  ...
  <button [disabled]="disableButton">Submit</button>
</form>

更新:

如果您想在值没有真正改变时将其禁用,请检查具有当前值的表单的当前值:

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;
  disableButton = true;

  userValue = {
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@domain.com' 
  }

  ngOnInit() {
    this.form = new FormGroup({
      firstName: new FormControl(),
      lastName: new FormControl(),
      email: new FormControl()
    });
    this.form.patchValue(this.userValue);
    this.form.valueChanges.subscribe(changes => this.wasFormChanged(changes));
  }

  private wasFormChanged(currentValue) {
    const fields = ['firstName', 'lastName', 'email'];

    for(let i = 0; i < fields.length; i++) {
      const fieldName = fields[i];
      if(this.userValue[fieldName] !== currentValue[fieldName]) {
        console.log('Came inside');
        this.disableButton = false;
        return;
      }
    }
    this.disableButton = true;
  }

}

注意: StackBlitz已相应更新。

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:1)

这称为Dirty Check

您可能会发现这样的答案非常有用: https://stackoverflow.com/a/50387044/1331040

此处是Template-Driven Forms的指南 https://angular.io/guide/forms

此处是Reactive Forms的指南 https://angular.io/guide/reactive-forms

这是两个概念之间的区别 https://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

希望这些帮助。

答案 2 :(得分:1)

我会做这样的事情:

  form: FormGroup;
  disableButton = true;
  originalObj: any;

  ngOnInit() {
    this.form = new FormGroup({
      control: new FormControl('Value')
    });

    this.originalObj = this.form.controls['control'].value; // store the original value in one variable

    this.form.valueChanges.subscribe(changes => {
      if (this.originalObj == changes.control)  // this if added for check the same value
      {
        this.disableButton = true;
      }
      else {
        this.disableButton = false;
      }
    }
    );
}

WORKING EXAMPLE

答案 3 :(得分:1)

onChange(targetValue : string ){  
console.log(targetValue );}
<input matInput placeholder="test" name="test" formControlName="testNM" (input)="onChange($event.target.value)">