首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角自定义构件中的不一致验证问题

角自定义构件中的不一致验证问题
EN

Stack Overflow用户
提问于 2018-09-13 21:35:19
回答 1查看 1.8K关注 0票数 25

为了展示一种真实世界的例子,让我们假设我们希望在我们的应用程序中使用@角/材料的数据报警器。

我们想要在很多页面上使用它,所以我们想让它很容易地添加到具有相同配置的表单中。为了满足这一需求,我们在带有<mat-datepicker>实现的ControlValueAccessor周围创建了一个自定义角度组件,以便能够在其上使用[(ngModel)]

我们希望处理组件中的典型验证,但同时,我们希望为包含我们的CustomDatepickerComponent的外部组件提供验证结果。

作为一个简单的解决方案,我们可以像这样实现validate()方法(innerNgModel来自导出的ngModel:#innerNgModel="ngModel" )。见本问题结尾处的完整代码):

代码语言:javascript
复制
validate() {
    return (this.innerNgModel && this.innerNgModel.errors) || null;
}

此时,我们可以以非常简单的方式(如我们所希望的那样)在任何形式的组件中使用数据报警器:

<custom-datepicker [(ngModel)]="myDate"></custom-datepicker>

我们还可以扩展上面的行,以获得更好的调试体验(如下所示):

代码语言:javascript
复制
<custom-datepicker [(ngModel)]="myDate" #date="ngModel"></custom-datepicker>
<pre>{{ date.errrors | json }}</pre>

只要我正在更改自定义数据报头组件中的值,一切都会正常工作。如果数据报警器有任何错误,则周围的表单仍然无效(如果数据报警器有效,则该表单将变为有效)。

但是!

如果外部表单组件的myDate成员(该成员作为ngModel传递)被外部组件(如:this.myDate= null)更改,则发生以下情况:

  1. writeValue()的CustomDatepickerComponent运行,它更新数据报警器的值。
  2. validate()的CustomDatepickerComponent运行,但此时innerNgModel未被更新,因此它返回早期状态的验证。

为了解决这个问题,我们可以从setTimeout中的组件发出一个更改:

代码语言:javascript
复制
public writeValue(data) {
    this.modelValue = data ? moment(data) : null;
    setTimeout(() => { this.emitChange(); }, 0);
}

在这种情况下,emitChange (广播自定义comoponent的更改)将触发新的验证。由于有了setTimeout,当innerNgModel已经更新时,它将在下一个循环中运行。

我的问题是,如果有比使用setTimeout?更好的方法来处理这个问题,如果可能的话,我会坚持使用模板驱动的实现。

提前感谢!

示例的完整源代码:

custom-datepicker.component.ts

代码语言:javascript
复制
import {Component, forwardRef, Input, ViewChild} from '@angular/core';
import {ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgModel} from '@angular/forms';
import * as moment from 'moment';
import {MatDatepicker, MatDatepickerInput, MatFormField} from '@angular/material';
import {Moment} from 'moment';

const AC_VA: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomDatepickerComponent),
    multi: true
};

const VALIDATORS: any = {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => CustomDatepickerComponent),
    multi: true,
};

const noop = (_: any) => {};

@Component({
    selector: 'custom-datepicker',
    templateUrl: './custom-datepicker.compnent.html',
    providers: [AC_VA, VALIDATORS]
})
export class CustomDatepickerComponent implements ControlValueAccessor {

    constructor() {}

    @Input() required: boolean = false;
    @Input() disabled: boolean = false;
    @Input() min: Date = null;
    @Input() max: Date = null;
    @Input() label: string = null;
    @Input() placeholder: string = 'Pick a date';

    @ViewChild('innerNgModel') innerNgModel: NgModel;

    private propagateChange = noop;

    public modelChange(event) {
        this.emitChange();
    }

    public writeValue(data) {
        this.modelValue = data ? moment(data) : null;
        setTimeout(() => { this.emitChange(); }, 0);
    }

    public emitChange() {
        this.propagateChange(!this.modelValue ? null : this.modelValue.toDate());
    }

    public registerOnChange(fn: any) { this.propagateChange = fn; }

    public registerOnTouched() {}

    validate() {
        return (this.innerNgModel && this.innerNgModel.errors) || null;
    }

}

以及模板(定制-datepicker.compnent.html):

代码语言:javascript
复制
<mat-form-field>
    <mat-label *ngIf="label">{{ label }}</mat-label>
    <input matInput
        #innerNgModel="ngModel"
        [matDatepicker]="#picker"
        [(ngModel)]="modelValue"
        (ngModelChange)="modelChange($event)"
        [disabled]="disabled"
        [required]="required"
        [placeholder]="placeholder"
        [min]="min"
        [max]="max">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <mat-error *ngIf="innerNgModel?.errors?.required">This field is required!</mat-error>
    <mat-error *ngIf="innerNgModel?.errors?.matDatepickerMin">Date is too early!</mat-error>
    <mat-error *ngIf="innerNgModel?.errors?.matDatepickerMax">Date is too late!</mat-error>
</mat-form-field>

周围的微模块(定制的datepicker.module.ts):

代码语言:javascript
复制
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MatDatepickerModule, MatFormFieldModule, MatInputModule, MAT_DATE_LOCALE, MAT_DATE_FORMATS} from '@angular/material';
import {CustomDatepickerComponent} from './custom-datepicker.component';
import {MAT_MOMENT_DATE_ADAPTER_OPTIONS, MatMomentDateModule} from '@angular/material-moment-adapter';
import {CommonModule} from '@angular/common';

const DATE_FORMATS = {
    parse: {dateInput: 'YYYY MM DD'},
    display: {dateInput: 'YYYY.MM.DD', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY'}
};

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        MatMomentDateModule,
        MatFormFieldModule,
        MatInputModule,
        MatDatepickerModule
    ],
    declarations: [
        CustomDatepickerComponent
    ],
    exports: [
        CustomDatepickerComponent
    ],
    providers: [
        {provide: MAT_DATE_LOCALE, useValue: 'es-ES'},
        {provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS},
        {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: false}}
    ]
})
export class CustomDatepickerModule {}

以及外部形式组件的部分:

代码语言:javascript
复制
<form #outerForm="ngForm" (ngSubmit)="submitForm(outerForm)">
    ...
    <custom-datepicker [(ngModel)]="myDate" #date="ngModel"></custom-datepicker>
    <pre>{{ date.errors | json }}</pre>
    <button (click)="myDate = null">set2null</button>
    ...
EN

回答 1

Stack Overflow用户

发布于 2019-04-05 07:43:33

我面临着同样的任务,在处理绑定和改变本地模式方面采取了不同的方法。

我没有分离和手动设置ngModelChange回调,而是将局部变量隐藏在两个getter\getter后面,其中调用了回调。

在您的示例中,代码如下所示:

custom-datepicker.component.html

代码语言:javascript
复制
<input matInput
        #innerNgModel="ngModel"
        [matDatepicker]="#picker"
        [(ngModel)]="modelValue"
        [disabled]="disabled"
        [required]="required"
        [placeholder]="placeholder"
        [min]="min"
        [max]="max">

custom-datepicker.component.ts期间

代码语言:javascript
复制
  get modelValue(){
      return this._modelValue;
  }

  set modelValue(newValue){
     if(this._modelValue != newValue){
          this._modelValue = newValue;
          this.emitChange();
     }
  }

  public writeValue(data) {
        this.modelValue = data ? moment(data) : null;
  }

您可以在https://github.com/cdigruttola/GestioneTessere/tree/master/Server/frontend/src/app/viewedit中看到实际的组件

我不知道这是否会产生影响,但我在测试应用程序时没有发现验证处理方面的问题,实际用户也没有向我报告过任何问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52322115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档