首页 > 解决方案 > Angular 5 - 如果不遵守其模式,则使用 debounceTime 更新表单,但输入除外

问题描述

我有一个带有 8 个输入的表单。无需输入。只有一个带有模式和垫子错误的输入。我使用 debounceTime 更新我的表单。这是我的html:

<form #formCard="ngForm" id="formCard">
<mat-form-field class="col-12">
        <input matInput 
    placeholder="{{ 'POSITION' | translate }}"
        type="text"
        name="position"
        [(ngModel)]="user.position"
    >
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'ADDRESS' | translate }}"
        type="address"
        name="address"
        [(ngModel)]="user.location.address"
    >
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'CITY' | translate }}"
        type="text"
        name="city"
        [(ngModel)]="user.location.city"
    >
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'POST_CODE' | translate }}"
        type="text"
        name="postal_code"
        [(ngModel)]="user.location.postal_code"
    >
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'COUNTRY' | translate }}"
        type="text"
        name="country"
        [(ngModel)]="user.location.country"
    >
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'CONTACT_EMAIL' | translate }}"
        type="text"
        name="contact_email"
        [(ngModel)]="user.contact_email"
        pattern="[a-zA-Z0-9.-.+]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}"
    >
        <mat-error>{{ 'REQUIRED_VALID_EMAIL' | translate }}</mat-error>
</mat-form-field>

<mat-form-field class="col-12">
        <input matInput
        placeholder="{{ 'CELLPHONE' | translate }}"
        type="text"
        name="cell_phone_number"
        [(ngModel)]="user.cell_phone_number"
    >
</mat-form-field>

这是我的组件

export class VcardComponent implements OnInit {

@ViewChild('formVcard') formVcard: any;

public ngOnInit() {
        this.user = this._user.getCurrentUser();
        if (!this.user.location) {
            this.user.location = new Location();
        }
        this.formVcard.valueChanges
              .pipe(debounceTime(500),distinctUntilChanged())
                          .takeWhile(() => this.alive)
                          .subscribe(res => {
            if (this.init == true) {
                this.updateUser(this.user);

            } else {
                this.init = true
            }
        });
}

public updateUser(user) {
        this.user = user;
        this._user.updateUser(this.user).takeWhile(() => this.alive).subscribe(res => {
                res = this.user;
        },error => {
            this._toasterService.pop('error', this._translate.instant("ERROR"))
            console.log(error);
        })
}

}

如果我的验证器不被尊重,我希望能够使用 debounceTime 更新我的表单,而不需要我的输入值,如果验证器被重新启动,则使用它。我怎样才能更新我的表格,也许focusout不用拆分它?多谢 :)

标签: angular5angular-material2

解决方案


推荐阅读