Angular Material 复选框验证

Angular Material Checkbox Validation

我想知道一种以相同样式验证所需复选框的方法 angular material 处理其他控件的验证 - 在表单提交时,控件显示为红色,除非被触摸。

我想我可以用 ng-style 做到这一点,但是,我想不出一种方法来检查表单是否已提交

这是 HTML

的片段
 <form [formGroup]="frmFinish" name="frmFinish">
        <mat-checkbox required formControlName="check1">Discussed Confidentiality and Information Sharing with Service User</mat-checkbox>
        <mat-checkbox required formControlName="check2">Discussed Disposal and Storage of Injecting Equipment and Substances</mat-checkbox>
        <mat-checkbox required formControlName="check3">Discussed Overdose Risk and Prevention</mat-checkbox>

        <mat-form-field>
            <textarea formControlName="note" [(ngModel)]="stepFive.note" matInput placeholder="Any Additional Notes" matTextareaAutosize matAutosizeMinRows="2" matAutosizeMaxRows="5"></textarea>
            <mat-hint align="end">This will be added to the profiles note's</mat-hint>
        </mat-form-field>

        <mat-card-actions>
            <button mat-raised-button type="button" class="nav-btn pull-right" (click)="fillForm()" style="background: red">Fill Form</button>
            <button mat-raised-button class="nav-btn pull-right" style="margin-left:5px;" (click)="createProfile()" type="submit">Finish</button>
            <button mat-raised-button matStepperPrevious class="nav-btn pull-right">Previous</button>
        </mat-card-actions>
    </form>

这是打字稿:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CreateProfileComponent } from '../create-profile.component';

@Component({
    selector: 'step-five-component',
    templateUrl: './step-five.component.html',
    styleUrls: ['../create-profile.component.css']
})
export class StepFiveComponent {
    frmFinish: FormGroup;

    stepFive = {
        note: null
    };

    constructor(private formBuilder: FormBuilder) {
        this.frmFinish = this.formBuilder.group({});
    }

    ngOnInit() {
        this.frmFinish = this.formBuilder.group({
            note: ['', Validators.required],
            check1: ['', Validators.required],
            check2: ['', Validators.required],
            check3: ['', Validators.required],
        });
    }

    createProfile(){
        if(this.frmFinish.valid){
            console.log('Creating profile..');
        }else{

        }
    }

    fillForm(){
        this.stepFive.note = 'asdasd';
    }

}

"however, I can't think of a way to check if the form has been submitted"。您可以在调用 createProfile 时将字段 isSubmitted 设置为 true 吗?

  createProfile(){
        this.isSubmitted = true;
        if(this.frmFinish.valid){
            console.log('Creating profile..');
        }else{

        }
    }

然后你可以使用 ngStyle 或 ngClass:

[ngClass]="{'has-error': checkForError() }"

这已在 Angular 版本 2.3.0 中得到解决。

只需使用:Validators.requiredTrue 而不是 Validators.required

(参见 GitHub 问题 #11459. See Angular docs requiredTrue