如何在同一组件中复用 Angular Material Datepicker 日期选择器
问题根源
报错的核心原因是模板引用变量重名冲突。你当前代码中使用#picker作为日期选择器的模板引用标识,同一个Angular模板内不允许存在重复的模板引用变量名。复用代码时如果第二个实例也使用#picker命名,框架无法识别绑定对应的日期选择器实例,就会抛出错误。
解决方案
方案1:零散复用场景(仅需少量复用)
每个日期选择器实例单独声明不重复的模板引用变量即可,示例如下:
<!-- 第一个日期选择器实例 --> <mat-form-field class="w-50 mt-2"> <mat-label>Date of Change</mat-label> <input matInput [matDatepicker]="picker" formControlName="firstDateOfChange" required placeholder="dd/MM/yyyy"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker startView="multi-year"></mat-datepicker> </mat-form-field> <!-- 第二个复用的日期选择器实例 --> <mat-form-field class="w-50 mt-2"> <mat-label>Other Date</mat-label> <input matInput [matDatepicker]="picker2" formControlName="secondDate" required placeholder="dd/MM/yyyy"> <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle> <mat-datepicker #picker2 startView="multi-year"></mat-datepicker> </mat-form-field>
方案2:高频复用场景(需要多次调用)
将日期选择器封装为独立的自定义组件,接收标签、表单控件、是否必填等参数作为输入,每个组件实例的模板变量是隔离的,不会出现重名冲突,同时减少重复代码。
自定义组件模板(date-picker.component.html)
<mat-form-field class="w-50 mt-2"> <mat-label>{{label}}</mat-label> <input matInput [matDatepicker]="picker" [formControl]="control" [required]="isRequired" [placeholder]="placeholder"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker startView="multi-year"></mat-datepicker> </mat-form-field>
自定义组件逻辑(date-picker.component.ts)
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-custom-date-picker', templateUrl: './date-picker.component.html' }) export class CustomDatePickerComponent { @Input() label: string = ''; @Input() control: FormControl = new FormControl(); @Input() isRequired: boolean = false; @Input() placeholder: string = 'dd/MM/yyyy'; }
父模板复用示例
<!-- 第一次复用 --> <app-custom-date-picker label="Date of Change" [control]="yourForm.get('firstDateOfChange')" [isRequired]="true"> </app-custom-date-picker> <!-- 第二次复用 --> <app-custom-date-picker label="Effective Date" [control]="yourForm.get('effectiveDate')" [isRequired]="true"> </app-custom-date-picker>
内容的提问来源于stack exchange,提问作者Enock Omondi
相关产品推荐
相关产品推荐

