You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中MatDatepicker添加按钮触发NullInjectorError如何解决

报错根因

触发NullInjectorError: R3InjectorError(AppModule)[MatDatepickerBase -> MatDatepickerBase -> MatDatepickerBase]的核心原因是matDatepickerCancel、matDatepickerApply两个指令放置位置错误:这两个指令必须作为<mat-datepicker>组件的子节点放在日期选择器面板内部,才能正确注入上层的MatDatepickerBase实例。你当前把两个按钮放在了<mat-form-field>下、<mat-datepicker>标签外部,Angular找不到对应的依赖实例就会抛出空注入错误。

另外模板还存在两个附带问题:

  • 第一个<mat-form-field>标签未正确闭合,缺少末尾的>
  • 输入框同时混用了[(ngModel)]双向绑定和响应式表单的formControlName,会造成值同步冲突、表单状态校验异常。
修复方案
  • 将带matDatepickerCancel、matDatepickerApply指令的两个按钮移动到<mat-datepicker #picker1>标签内部,作为日期选择器弹出面板的自定义操作项
  • 补全第一个<mat-form-field>缺失的闭合尖括号
  • 移除输入框上冗余的[(ngModel)]绑定,统一使用响应式表单API获取、设置日期值,避免双绑冲突
修复后参考代码
<div class="container">
  <form [formGroup]="dateRangeForm" (ngSubmit)="onFormSubmit()" class="cal">
    <mat-form-field>
      <input 
        matInput 
        [min]="minDate" 
        [matDatepicker]="picker1" 
        placeholder="Start date"  
        formControlName="fromDate" >
      <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
      <mat-datepicker #picker1>
        <!-- 操作按钮放在日期选择器组件内部 -->
        <button mat-button matDatepickerCancel>Cancel</button>
        <button mat-raised-button color="primary" matDatepickerApply>Apply</button>
      </mat-datepicker>
    </mat-form-field>

    <mat-form-field>
      <input 
        [min]="dateRangeForm.get('fromDate')?.value" 
        matInput 
        [matDatepicker]="picker2" 
        placeholder="End date"  
        formControlName="toDate">
      <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
      <mat-datepicker #picker2></mat-datepicker>
    </mat-form-field>

    <br>
    <button 
      type="submit" 
      class="submit" 
      [disabled]="!dateRangeForm.get('fromDate')?.value || !dateRangeForm.get('toDate')?.value">
      Borrow
    </button>
    &nbsp;&nbsp;&nbsp;&nbsp;
  </form>
</div>

修复后不需要单独声明loaned_at、return_date变量,直接通过dateRangeForm.get('fromDate').value、dateRangeForm.get('toDate').value即可获取选中的起止日期,表单状态也会被响应式表单统一托管。


内容的提问来源于stack exchange,提问作者Bilal S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 12:12:09