如何使用 Angular 2 检查表单的变化

新手上路,请多包涵

我有一个包含少量数据字段和两个按钮的表单。我只想在用户对表单进行一些更改时启用按钮。我试过使用:

 this.form.valueChanges.subscribe(data => console.log('form changes', data));

但是当表单加载时,最初也会检测到这些变化。有没有其他方法可以检查表单中的任何更改。我希望它仅在用户更改字段时调用,而不是在加载表单时调用。以下是我的 html 和打字稿代码:

profile.html:

 <section>
    <div>
        <form [formGroup]="form">
            <fieldset>
                <div class="panel-group m-l-1 m-r-1 accordion vertical-scroll" id="">
                    <div class="form-group required no-gutter">
                        <label for="firstname"> First Name:</label>
                        <div class="col-md-7 col-lg-6">
                            <input type="text" class="form-control" id="firstname" placeholder="" name="firstname" title="firstname" formControlName="firstname" size="128" aria-required="true" maxlength="35">
                        </div>
                    </div>
                </div>

            </fieldset>
            <div>
                <button class="btn btn-primary" type="button" (click)="save()">Save</button>
                <button class="btn btn-primary" type="button" (click)="cancel()">Cancel</button>
            </div>
        </form>
    </div>
</section>

profile.component.ts:

 export class ProfileComponent implements OnInit, AfterViewInit, OnChanges {
    public form: FormGroup;

    constructor(private formBuilder: FormBuilder, private app: Application) {

    }

    loadForm(): void {
        this.form = this.formBuilder.group({
            firstname: [this.app.firstName, Validators.required]
        });
        this.form.valueChanges.subscribe(data => console.log('form changes', data));

    }

    save(): void {

    }

    cancel(): void {

    };

    ngOnInit() {
        this.loadForm();
    }

    ngAfterViewInit() {
        this.loadForm();
    }
}

原文由 Valla 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 546
1 个回答

有一个答案

https://stackoverflow.com/a/63488981/11186896

当数据变回 defaultValue 时,您可以使用 markAsPristine 方法将原始状态设置为 true,如下所示:

 ngOnInit() {
    const defaultValue = this.registrationForm.value;
    this.registrationForm.valueChanges
      .pipe(debounceTime(200))
      .subscribe(value => {
        if (JSON.stringify(defaultValue) == JSON.stringify(value)) {
          this.registrationForm.markAsPristine();
        }
      });
  }

原文由 bug5layer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进