角材料matDatepicker和Textarea作为表单的一部分

时间:2018-07-30 18:48:45

标签: angular forms datepicker angular-material textarea

在我的Angular应用中,我有一个表格。用户应在此表格中输入以下内容:

  1. 开始日期
  2. 结束日期
  3. 某些文本进入文本区域

我在开始日期和结束日期输入中使用了角材料“ Datepicker”:

    <form #f="ngForm" (ngSubmit)="onSubmit(f)" fxLayout="column" fxLayoutAlign="center"> 
      <mat-form-field>
        <input matInput [matDatepicker]="picker1" placeholder="Select Start Date" ngModel #beginningInput="ngModel" name="beginning" type="date" required>
        <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
        <mat-datepicker #picker1></mat-datepicker>
        <mat-error *ngIf="beginningInput.hasError('required')">
            Start date is required.
        </mat-error>   
      </mat-form-field>
      <mat-form-field>
        <input matInput [matDatepicker]="picker2" placeholder="Select End Date" ngModel #endInput="ngModel" name="end" type="date" required>
        <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
        <mat-datepicker #picker2></mat-datepicker>
        <mat-error *ngIf="endInput.hasError('required')">
            End date is required.
        </mat-error>   
      </mat-form-field>
      <mat-form-field>
         <textarea matInput placeholder="Textarea" ngModel #textInput="ngModel" name="description" ></textarea>
      </mat-form-field>
      <div class="gap"></div>
      <div class="buttons">
        <button class="cancelButton" mat-raised-button color="primary" [mat-dialog-close]>Cancel</button>
        <button class="submitButton" mat-raised-button color="primary" [disabled]="isDisabled">Submit</button>    
      </div>  
    </form>

提交表单后,应该保存开始日期,结束日期和文本区域的内容,然后进行处理。因此,在.ts文件中,有以下代码(为完整起见,我将其包括在内):

onSubmit(form: NgForm) {

     this.beginning = form.value.beginning;
     this.end = form.value.end;
     this.description': form.value.description;

     //more code

}

但是,该表单仍然无效,也就是说,我无法提交该表单,请参见以下屏幕截图:

enter image description here

鉴于我要执行的操作,我不确定以下几行是否正确:

<input matInput [matDatepicker]="picker1" placeholder="Select Start Date" ngModel #beginningInput="ngModel" name="beginning" type="date" required>

<input matInput [matDatepicker]="picker2" placeholder="Select End Date" ngModel #endInput="ngModel" name="end" type="date" required>

<textarea matInput placeholder="Textarea" ngModel #textInput="ngModel" name="description" ></textarea>

我的代码有问题吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

Submit按钮保持为disabled的原因可能是,一旦表格有效,您就永远不会将isDisabled的值更改为false。

您还可以直接检查表单的有效性

[disabled]="f.invalid"

html代码

<button class="submitButton" mat-raised-button color="primary" [disabled]="f.invalid">Submit</button>