使用 Angular,我在循环中使用这个日期时间选择器,我需要分配一个唯一的引用。到目前为止,我将其硬编码为
req_d1
但它会产生一些问题。我想知道如何使用 Angular 在循环中设置动态唯一引用,谢谢!
备注:行数也是动态的,可以是0、1、20,甚至更多。
<tr *ngFor="let row of rows; let i = index">
<td>{{ row.name }}</td>
<td>
<input
type="text"
name="date{{i}}"
[value]="row.planned_date"
(blur)="updatePlannedDate(row, $event)"
[owlDateTime]="req_d1"
[owlDateTimeTrigger]="req_d1"
/>
<owl-date-time
#req_d1
[pickerType]="'calendar'"
></owl-date-time>
</td>
<td>
这是由于与使用
[value]
相关的一些奇怪的错误,而是使用模板驱动的角度形式的 [(ngModel)]
。当我们使用这个指令并且它做了同样的事情时,这个错误就不会发生。
<input
type="text"
name="date{{i}}"
[(ngModel)]="row.planned_date"
*ngIf="req_d1.formatString"
[owlDateTime]="req_d1"
[owlDateTimeTrigger]="req_d1"
/>
import { Component, importProvidersFrom } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { CommonModule } from '@angular/common';
import {
OwlDateTimeModule,
OwlNativeDateTimeModule,
} from '@danielmoncada/angular-datetime-picker';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [
CommonModule,
OwlDateTimeModule,
OwlNativeDateTimeModule,
ReactiveFormsModule,
FormsModule,
],
template: `
<div *ngFor="let row of rows;trackBy: trackByFn; let i = index">
<div>{{ row.name }}</div>
<div>
<owl-date-time
#req_d1="owlDateTime"
[pickerType]="'calendar'"
></owl-date-time>
<input
type="text"
name="date{{i}}"
[(ngModel)]="row.planned_date"
*ngIf="req_d1.formatString"
[owlDateTime]="req_d1"
[owlDateTimeTrigger]="req_d1"
/>
</div>
<div>
`,
})
export class App {
rows = [
{ name: 1, planned_date: new Date() },
{ name: 2, planned_date: new Date() },
{ name: 3, planned_date: new Date() },
{ name: 4, planned_date: new Date() },
];
trackByFn(index: number) {
return index;
}
}
bootstrapApplication(App, {
providers: [
provideAnimations(),
importProvidersFrom([OwlDateTimeModule, OwlNativeDateTimeModule]),
],
});