Angular 4.4 w / Material 2中的条件验证

时间:2017-10-20 16:50:52

标签: angular angular-material2 angular-forms

我的模板驱动表单上有一个名为Status的字段&用户可以将其设置为DraftPublish

要求是,当status值设置为publish时,表单UI上的几乎所有元素都必须更新,以显示它们现在已成为required。相反,当它被设置回draft时,只有一个字段(标题字段)需要required

解决这个问题的诀窍是什么?

我整理了以下示例表格片段以讨论此事。

<form class="example-form" novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">

       <mat-button-toggle-group #group="matButtonToggleGroup" matInput name="status" [(ngModel)]="status" #field_status="ngModel">
          <mat-button-toggle value="draft">
             DRAFT
          </mat-button-toggle>

          <mat-button-toggle value="publish">
             PUBLISH
          </mat-button-toggle>
    </mat-button-toggle-group>

    <mat-form-field class="example-medium-width">
        <input matInput name="title" [(ngModel)]="title" placeholder="Title" required  #field_title="ngModel">
        <mat-error *ngIf="field_title.invalid">
            Title is <strong>required</strong>.
        </mat-error>
    </mat-form-field>

    <p>&nbsp;</p>

    <mat-form-field class="example-medium-width">
        <textarea matInput name="description" [(ngModel)]="description" placeholder="Description" maxlength="50" #field_description="ngModel"></textarea>
        <!-------------------------------------
          how do we make this ALSO required, 
          if the status field is set to publish?
        --------------------------------------->
    </mat-form-field>


    <button [disabled]="!f.form.valid">Submit</button><br>
    <!----------------------------------------------
    the button will not allow the form to submit 
     if title is left blank (when status is draft). 
     BUT, if the status is set to publish, 
     then title alone is not good enough. 
     both Title and Description needs to be filled in! -->


</form>

0 个答案:

没有答案