代码之家  ›  专栏  ›  技术社区  ›  Elaine Byene

使用Angular 17在编辑表单中绑定保存的日期

  •  2
  • Elaine Byene  · 技术社区  · 2 年前

    我有一个表格,其中输入并保存了日期,但当我编辑表格时,日期没有绑定。

    JSON:

    "checkOut": {
        "runDate": "2024-07-05T09:42:00.000Z",
    }
    

    形式为:

    <input type="datetime-local" [(ngModel)]="checkOut.runDate">
    

    日期通过绑定显示如下:

    {{source.room.checkOut?.runDate | date:"dd MMM, yyyy"}}
    

    当我去编辑表单时,我想要输入字段 [(ngModel)]="checkOut.runDate" 如果已输入日期,则要预先填写。我怎样才能做到这一点?

    1 回复  |  直到 2 年前
        1
  •  2
  •   Naren Murali    2 年前

    本地日期时间例外输入类似 2024-07-05T09:42:00 ,所以我们可以对其进行转换以满足要求。

    ngOnInit() {
        this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0];
    }
    

    完整代码:

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [FormsModule, CommonModule],
      template: `
       <input type="datetime-local" [(ngModel)]="checkOut.runDate">
       <br/>
       {{checkOut.runDate | date:"long"}}
      `,
    })
    export class App {
      checkOut: any = {
        runDate: '2024-07-05T09:42:00.000Z',
      };
    
      ngOnInit() {
        this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0];
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo