将模板形式的datetime-local输入重置为原始(ngModel)值

时间:2019-05-13 16:04:56

标签: angular

我的Angular 6模板表单加载了最新数据。用户可以在datetime-local输入中更改日期/时间,但是我不知道如何将其重置回原始日期/时间(从数组中加载到ngModel中。“ one.classTimesLogOffRevised”),如果用户想要取消。我可以清除输入的日期,但是按取消按钮之前输入的任何日期值都将保留并发布到ngModel(因此更改日期)。
我删除了重置日期的蓝色“ X”,因为这使单击时所有内容都为空(不需要)。 我在这里面临的部分挑战是,我使用的是相同的ngModel,新值将覆盖旧值。但是应该有一种方法可以还原旧的值..?

我尝试使用markAsPristine()方法,我认为应该可以(再次,这是模板驱动的形式),但是它什么也不会重置。有关用法示例,请参见我的代码。

   <form (ngSubmit)="onSubmit(revisedRecord)" novalidate 
 #revisedRecord="ngForm">
 <div *ngFor="let one of editOneLogIn; let in = index"> 

   <label for="name">Additional REVISED Student Check-Out Time</label>
   <p>Revised Check-Out Time: {{ one.classTimesLogOffRevised  | date: 
  'medium' }} </p>

 <input type="datetime-local" [ngModel]="one.classTimesLogOffRevised | 
 date: 'medium' "
 (ngModelChange)="classTimesLogOffRevised=$event" 
 name="ClassTimesLogOffRevised"
  [ngModel]="ClassTimesLogOffRevised | date: 'medium' " 
 (ngModelChange)="ClassTimesLogOffRevised=$event"
  required  #dateClear class="form-control">

   <button type="button" class="btn btn-light"  
  (click)="cancelTimeChange()" >cancel</button> 

 <!-- This works, but does not set back to original value  -->
 (click)= "dateClear.value = ''"

 </div> </form>

Component.ts ...

 import { Component, OnInit, ViewChild } from '@angular/core';
 import { ActivatedRoute, Params, Router, ExtraOptions } from 
 '@angular/router';
 import { DataStorageService } from 'src/app/shared/data-storage.service';
 import { NgForm } from '@angular/forms';

 @Component({
   selector: 'app-teacheredit',
   templateUrl: './teacheredit.component.html',
   styleUrls: ['./teacheredit.component.css']
 })
 export class TeachereditComponent implements OnInit {

   @ViewChild('revisedRecord') slForm: NgForm;

...

  cancelTimeChange() {

 // this does not reset anything in the form (no errors)

 this.slForm.form.markAsPristine();
  }

1 个答案:

答案 0 :(得分:0)

要获得预期结果,请在选项下更改onclick事件以将日期设置为初始值

(click)="dateClear.value = one.classTimesLogOffRevised"

代码示例以供参考-https://codesandbox.io/s/angular-kbw7z

注意:要为使用datetime-local的输入设置日期,值应始终设置为yyyy-MM-ddThh:mm

有关日期时间本地输入-https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

的详细信息,请参阅MDN。
相关问题