Angular Material - show mat-error on button click

2020-05-30 04:18发布

I am trying to do validation using the <mat-for-field> and <mat-error>. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.

This is my code:

HTML:

<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

TS:

dueDateValidator: FormControl = new FormControl('', [Validators.required]);

9条回答
三岁会撩人
2楼-- · 2020-05-30 04:43

the easiest way is call markUserNameTouched() method as below on button click on template. We use markAsTouched() on formControl.

public staffLoginForm: FormGroup;
ngOnInit(){
this.staffLoginForm = new FormGroup({
username: new FormControl(null),
password: new FormControl(null)});

markUserNameTouched():void{
  this.staffLoginForm.get('username').markAsTouched();
}
查看更多
欢心
3楼-- · 2020-05-30 04:44

Angular 8 has a new forms method: markAllAsTouched();

This will mark a control/form and ALL DESCENDANTS as touched!!!

So:

this.form.markAllAsTouched();

Is the solution.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-05-30 04:49

Either you can do as "Kyle Pfromer" suggested or as you are using form group, you can mark element as touched on submit with

onSubmit(){ this.formName.get('formControlName').markAsTouched(); }
查看更多
登录 后发表回答