【问题标题】:How to check for state change in angular 4/6?如何检查角度 4/6 的状态变化?
【发布时间】:2018-12-27 19:19:40
【问题描述】:

我的任务是创建一个帐户信息网页,该网页由 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>

我的代码输出:

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    由于您使用的是响应式表单,因此您可以在 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 供您参考。

    【讨论】:

    • 你能分享一个代码sn-p。我还是不明白。
    • @MadhavanSundararaj,刚刚为您的参考添加了一个工作示例 stackblitz。
    • 如果Value 被用户删除并再次输入怎么办?
    • 它正在工作,但如果我清除它并写入相同的值,它仍然启用。有什么办法也可以检查吗?谢谢你的回答。
    • @MadhavanSundararaj,我已经用您想要的修复程序更新了我的答案。我认为它现在应该可以工作了。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这称为Dirty Check

      您可能会发现这个 SO 答案非常有用: 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/

      希望这些帮助。

      【讨论】:

        【解决方案4】:

        我会这样做:

          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

        【讨论】:

        • 这很好用。这里的控制是什么?我的 ts this.form = new FormGroup ({ givenName: new FormControl(user.givenName), familyName: new FormControl(user.familyName), email: new FormControl(user.email), });跨度>
        • 它是您要检查的控件的名称
        • 如果有 givenName 控制则 changes.givenName, changes.familyName, changes.email
        • 尝试优化,因为我赶时间所以无法做到这一点
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-08
        • 1970-01-01
        • 1970-01-01
        • 2018-12-22
        • 2019-04-15
        • 2018-01-22
        • 1970-01-01
        相关资源
        最近更新 更多