Angular 是否有一种方法将模板驱动的表单标记为initialy“;“感动”;没有设置超时?

Angular 是否有一种方法将模板驱动的表单标记为initialy“;“感动”;没有设置超时?,angular,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&g

因此,让我们有投入

<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>
有没有不设置超时的方法?现在,它被延迟是为了让表单初始化自己使用
AfterViewInit
init钩子没有帮助


您可以在查看初始化后尝试

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;
    }
}

查看演示,您似乎希望在用户触摸之前显示“必需”错误状态

如果是这种情况,您可以实现自定义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)));
  }
}

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

@Downvoter-很清楚我将在这里实现什么-从
onInit
中删除
setTimeout
。“如何改进才能让你更清楚?把它放进去有帮助吗?”TamásSzabó测试过,noI认为你没有给出这个例子。此外,这是行不通的。
export class ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.touched || (form && form.submitted)));
  }
}