我的模板驱动表单上有一个名为Status
的字段&用户可以将其设置为Draft
或Publish
。
要求是,当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> </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>