【问题标题】:Update input type time based on updated FormControl using PatchValue or SetValue in Angular在 Angular 中使用 PatchValue 或 SetValue 根据更新的 FormControl 更新输入类型时间
【发布时间】:2021-06-08 16:05:33
【问题描述】:

我有一个包含 3 个输入的表单组。第一个输入是时间输入,另外两个是自定义表单组件。我设置了一个 form.patchValue 来更新表单值,如下所示,但是它不会更新 UI,时间输入仍然是空的。

如何使用 patchValue 更新输入?

    this.scheduleAutoReportForm = new FormGroup(
      {
        reportAt: new FormControl( '12:00' , Validators.required),
        days: new FormControl([],Validators.required),
        email: new FormControl([],[Validators.required])
      }
    );

    this.scheduleAutoReportForm.patchValue({
      reportAt: '24:00',
      days:["2","4"],
      email: ['placeholder@gmail.com'] 
    });

this.ref.detectChanges();

更新

我进行了实验,结果是文本框更新了,但时间没有更新。

  <div class="modal-header">
    <h4 class="h-primary modal-title">Schedule Auto Report</h4>
    <mh1-icon-button [icon]="faTimes" [iconClasses]="['btn', 'btn-sm', 'mx-0']" iconSize="lg" (click)="closeModal()">
    </mh1-icon-button>
  </div>

  <div class="modal-body card">
    <!-- This is where the form starts -->
    <form [formGroup]='scheduleAutoReportForm' (ngSubmit)='onSubmit()'>

      <div class="row">
        <div class="col-3">
          <label for="reportAt" ><h5>Send Report At:</h5></label>
          <input type="time" name='reportAt' formControlName='reportAt' class="form-control" required>
        </div>
      </div>

      <div class="row">
        <div class="col-3">
          <label for="test" >test</label>
          <input type="text" name='test' formControlName='test' class="form-control" >
        </div>
      </div>

      <div class="row mt-2">
        <div class="col-12">
        <sentryx-day-selector formControlName="days"></sentryx-day-selector>
        </div>
      </div>


      <div class="row mt-2">
        <div class='col-12'>
          <sentryx-email-chips formControlName="email"></sentryx-email-chips>
        </div>
      </div>

      <div class="row mt-5">
        <div class="col-12">
          <button type="submit" class="btn btn-md btn-secondary"
            [disabled]="!scheduleAutoReportForm.valid">Submit</button>
          <button type="cancel" class="btn btn-md btn-secondary">Cancel</button>
        </div>
      </div>

    </form>
  </div>

  <div class="modal-footer card">
    {{scheduleAutoReportForm.value | json}}
    {{schedule | json}}
  </div>


【问题讨论】:

  • 由于某种原因,HTML 页面没有更新。重新启动 NPM 完成了这项工作。

标签: html angular angular-reactive-forms angular-forms angular-formbuilder


【解决方案1】:

您是否尝试在修补值后调用 updateValueAndValidity()? 见

What is updateValueAndValidity

【讨论】:

  • 为什么你认为这会有用?
  • 我试过 this.scheduleAutoReportForm.get('reportAt').updateValueAndValidity({ onlySelf: true, emitEvent: false }); 没用
  • 你能把 html 和完整的组件贴出来吗?我的另一个猜测是您设置的值不正确。表单控件和组有时处理起来很烦人。
  • 所以我对它进行了试验,我正在使用时间输入。我制作了一个文本框并填充了该文本框
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 2019-04-06
  • 2018-09-21
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多