【问题标题】:How to set input field with current date in angular如何以角度设置具有当前日期的输入字段
【发布时间】:2020-03-24 08:26:52
【问题描述】:

我希望我的表单日期输入字段在我打开表单时显示今天的日期,例如 (2019-11-28)。我看到了很多关于它如何在 AngularJs 中工作的示例,但是我如何才能使用响应式表单获取日期。

表格

//.....
<div class="form-group">
  <label>Date:</label>
      <div class="input-group">
        <input type="date" class="form-control col-md-8" formControlName="date"/>
      </div>
</div>
.
//...

使用 formControlName。

.ts

//...
currentD = new Date();

..
..
//....

【问题讨论】:

    标签: html angular


    【解决方案1】:

    创建一个 FormGroup 变量以将值赋给 Form

     form : FormGroup;
    
     // you can set the default value
    constructor( fb:FormBuilder){
       this.form = fb.group({
          presentDate: [new Date()]
       });     
    }
    

    在视图中

    <div class="form-group">
     <form [formGroup] = "form">
      <label>Date:</label>
          <div class="input-group">
            <input type="date" class="form-control col-md-8" formControlName="presentDate"/>
          </div>
    </div>
    

    【讨论】:

      【解决方案2】:

      设置formControlName默认值为(new Date()).toISOString().substring(0,10)

      Working Demo

      试试这样:

      .ts

      myForm:FormGroup;

      this.myForm = new FormGroup({    
       'presentDate': new FormControl((new Date()).toISOString().substring(0,10))
      });
      

      【讨论】:

        【解决方案3】:

        使用数据绑定,你可以使用一种方式绑定

        &lt;input type="date" [value]="currentD" class="form-control col-md-8" formControlName="date"/&gt;

        或tuo方式绑定

        &lt;input type="date" [(ngModel)]="currentD" class="form-control col-md-8" formControlName="date"/&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-09-17
          • 1970-01-01
          • 2013-04-15
          • 2018-09-29
          • 1970-01-01
          • 2012-12-21
          • 2019-07-11
          相关资源
          最近更新 更多