Angular:下一次运行代码的最佳方法是什么?

时间:2018-11-28 14:23:09

标签: angular

我正在为输入(mat-input)编写模糊处理程序,如果表单有效,它将处理DOM。我想确保现在不会出现验证错误,这就是为什么我将代码包装在setTimeout中以便在下一个刻度上运行它的原因?

是否有很好的Angular方法在下一个刻度上运行一些代码?

1 个答案:

答案 0 :(得分:0)

在模糊Stack Blitz上显示和隐藏错误消息的输入示例

问题:是否有很好的Angular方法在下一个刻度上运行一些代码?

答案:是的!使用Angular表单控件来管理表单状态。角度更新会自动进行。

import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  input = new FormControl('', {
    validators: [Validators.required, Validators.minLength(3)],
    updateOn: 'blur'
  });

  getErrorMessage() {
    return this.input.hasError('required') ? 'You must enter a value' :
      this.input.hasError('minlength') ? 'Minimum length is 3 characters' :
        '';
  }
}



<mat-card class="searchbox">
<mat-form-field>
    <input matInput  placeholder="Enter three of more characters" [formControl]="input" required>
    <mat-error *ngIf="input.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
<button mat-stroked-button>GO</button>

相关问题