'required'不适用于带有表单的输入标签

时间:2019-07-12 17:08:28

标签: html angular

我只是想将表单的字段设为必填字段,以便您不能将其提交为空白,但是我遇到了问题。只有我的“描述”必需属性可以正常工作。其他字段仅突出显示红色,但实际上并未阻止提交。

我尝试将必填项放在mat-form-field中无济于事,并关闭输入标签。

<h1 mat-dialog-title>Add New Announcement</h1>
<form (submit)="onSubmitAnnouncement(newAnnouncementForm)" #newAnnouncementForm="ngForm">
    <div mat-dialog-content>
        <mat-label for="title">Post Title</mat-label>
        <mat-form-field>
            <input maxlength="55"
            type="text" 
            matInput 
            name="title" 
            id="title" 
            ngModel 
            #title="ngModel"
            required/>
            <mat-error *ngIf="title.invalid">Title is required</mat-error>
        </mat-form-field>
        <p>Description:</p>
        <mat-form-field>
            <textarea rows="6" cols="50" maxlength="500"
            type="text" 
            matInput 
            name="description" 
            id="description" 
            ngModel 
            #description="ngModel" 
            required>
            <mat-error *ngIf="description.invalid">Description is required</mat-error>
            </textarea>
        </mat-form-field>
        <p>Audience:</p>
        <mat-form-field>
            <mat-label>Select Audience</mat-label>
            <mat-select [(ngModel)]="selectedAudience" name="aud" required>
                <mat-option *ngFor="let audience of audiences" [value]="audience.value">
                    {{audience.viewValue}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
    <div mat-dialog-actions>
        <button mat-button type="button" (click)="onCancel()">Cancel</button>
        <button mat-button type="submit" cdkFocusInitial>SUBMIT</button>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

您可以尝试创建自己的服务(例如validate-form.service)。然后,您可以自定义检查每个输入字段。这种方法一直对我有用!