有没有办法将模板驱动的表单标记为初始化“触摸”而没有setTimeout?

时间:2018-05-10 08:10:22

标签: angular

所以我们有输入

<form novalidate #f="ngForm">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" name="myname" required [(ngModel)]="comment">
    <mat-error>Is required lol</mat-error>
  </mat-form-field>

我希望它在init上无效,所以我“触摸”它

export class InputOverviewExample implements OnInit {
  comment = null;
  @ViewChild('f')
  form: NgForm


  ngOnInit() {
    setTimeout(() => {
      console.log(this.form.controls);
    console.log(typeof this.form.controls);
    console.log(Object.keys(this.form.controls));

    console.log(this.form.controls.myname);
    console.log(this.form.controls['myname']);
    this.form.controls.myname.markAsTouched();
    })
  }

有没有办法在没有设置超时的情况下执行此操作?现在,它被推迟以便让表单初始化自己。 使用AfterViewInit init hook无效

https://stackblitz.com/edit/angular-urqles-rbmto8

2 个答案:

答案 0 :(得分:0)

看看您的演示,您似乎想在用户触摸它之前显示“必需”错误状态。

在这种情况下,您可以实现自定义ErrorStateMatcher。

class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control, form) {
    return !!(control && control.invalid);
  }
}

使用MyErrorStateMatcher,只要输入无效(甚至在用户触摸之前),isErrorState就会返回true。

(默认的ErrorStateMatcher如下所示:

export class ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.touched || (form && form.submitted)));
  }
}

使用默认错误状态匹配器,isErrorState在用户触摸该字段之前不会返回true)

答案 1 :(得分:-1)

您可以尝试AfterViewInit,如下所示:

export class InputOverviewExample implements OnInit, AfterViewInit {
comment = null;
@ViewChild('f') protected f;
form: NgForm


ngOnInit() {
}

    public ngAfterViewInit() {
    console.log(this.f);
    this.f.touched= true;
    }
}

Demo