【问题标题】:Angular input update validatorsAngular 输入更新验证器
【发布时间】:2019-05-07 01:19:39
【问题描述】:

我正在使用 Angular 6 进行开发,我已经实现了如下输入(角度材料框架的垫输入),并且我已经将 id 分配给了 FormGroup 验证器。当我初始化打字稿类时,我更新了输入值,但验证器没有看到,当我用 this.formGroup.valid 检查它时,它返回 false,但值是正确的。这是我的代码

constructor(...) {

    this.formGroup = formBuilder.group({
        id_conto: [Validators.required, Validators.pattern("[0-9]+")],
        channel: [Validators.required, Validators.pattern("[0-9]+")],
        automatic_size: [],
        pip_stoploss: [Validators.required, Validators.pattern("[0-9]+")]
    });


    this.user = api.getUser();
    this.user.subscribe((response) => {
        this.userInstance = response;
    });

    this.editClicked();
}

editClicked() {
    if (this.formGroup.valid) {
        this.editing = !this.editing;
        if (!this.editing)
            this.formGroup.disable();
        else
        this.formGroup.enable();
    }
}

还有我的html代码

<mat-form-field class="form-full-width">
          <input matInput placeholder="Channel" formControlName="channel"
                 [errorStateMatcher]="matcher" [value]="userInstance.channel">
          <mat-error *ngIf="formGroup.get('channel').hasError('pattern') && !formGroup.get('channel').hasError('require')">
            Inserisci un valore numerico
          </mat-error>
          <mat-error *ngIf="formGroup.get('channel').hasError('require')">
            Inserire un valore
          </mat-error>
        </mat-form-field>

【问题讨论】:

  • 您必须离开该字段 (blur) 才能看到显示您有错误的视图返回。应该更新表单,而不是控件本身。考虑在 stackblitz.com 上提供minimal reproducible example
  • 你对(模糊)是什么意思
  • blurfocus 相反:通过单击其他任何位置离开输入,触发 blur 事件
  • @AlesandroGiordano 将其更改为不需要 formGroup.get('channel').hasError('require')
  • @NarendraSinghRathore 没有任何改变

标签: javascript node.js angular typescript angular-cli


【解决方案1】:

您正在使用响应式表单。要更新表单控件值,请使用您的表单对象而不是模板内部。

删除:

[value]="userInstance.channel"

改为:

this.user.subscribe((response) => {
  this.userInstance = response;
  this.formGroup.controls.channel.setValue(this.userInstance.channel);
});

这也应该更新可见值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2021-08-18
    相关资源
    最近更新 更多