反应式形式的 NgbDatepicker:设置初始值

Mic*_*man 4 date angular-bootstrap angular angular-reactive-forms ngb-datepicker

这可能是我一段时间以来处理过的最令人沮丧的问题之一。一般来说,日期,尤其是 NgbDatepicker 在 Angular 中处理起来有点麻烦。

我正在 Angular 8 中针对反应​​式表单实现 NgbDatepicker,我的问题的要点是我可以设置日期控件的初始值,但该初始值不会(视觉上)显示在表单上。我可以将表单记录到控制台并看到该值已设置,但表单字段本身并未更新。如果我从选择器本身选择一个日期,那么我的选择会反映在表单字段中。我原以为这就像设置[startDate]ngbDatepicker 输入的属性一样简单,但显然不是。我对此尝试了很多不同的迭代;这就是代码方面的情况:

我的HTML:

<input #licenseExpiration="ngbDatepicker"
    class="form-control"
    fromControlName="licenseExpiration"
    [startDate]="startDate"
    ngbDatepicker />
<button class="btn btn-info zero-spacing pt-1 pr-1 pl-1"
    (click)="licenseExpiration.toggle()"
    type="button">
Run Code Online (Sandbox Code Playgroud)

我的组件的相关部分:

@Component({
  selector: 'app-cert',
  templateUrl: './cert.component.html',
  providers: [
    { provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }
  ]
})
export class CertComponent implements OnInit {
  certForm: CertForm = new CertForm();

  constructor(
    public readonly formatter: CustomDateParserFormatter) { }

  ngOnInit() {
    this.certForm.setModel(...modelObjectFromOtherService...);
  }

  get startDate() {
    return { year: 2020, month: 6, day: 13 };
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的 HTML 驻留在由该 CertForm 类型指定的 formGroup 中。该表单包含日期控件,看起来(部分)如下所示:

export class CertForm extends FormGroup {
  public dateParser: CustomDateParserFormatter;

  constructor(
    cert: ICertModel = new CertModel()) {
    super({
      ..
      licenseExpiration: new FormControl("", Validators.required),
      ..
    });
  }

  setModel(cert: ICertModel) {
    this.patchValue({
      licenseExpiration
    });
  }

  getModel(): ICertModel {
    const cert = new CertModel();
    ...
    cert.licenseExpiration = this.get("licenseExpiration").value;
    ...
    return cert;
  }
}
Run Code Online (Sandbox Code Playgroud)

从那里我确实有了自定义解析器/格式化程序设置,它看起来就像 NGB 示例页面上指定的那样:

@Injectable({
  providedIn: "root"
})
export class CustomDateParserFormatter extends NgbDateParserFormatter {

  readonly DELIMITER = '/';

  parse(value: string): NgbDateStruct | null {
    if (value) {
      let date = value.split(this.DELIMITER);
      return {
        day: parseInt(date[0], 10),
        month: parseInt(date[1], 10),
        year: parseInt(date[2], 10)
      };
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ? date.month + this.DELIMITER + date.day + this.DELIMITER + date.year : '';
  }
}
Run Code Online (Sandbox Code Playgroud)

而且,这似乎不允许我用可见的启动值启动该日期字段。正如您所看到的,此时我只是对开始日期的返回值进行硬编码。该日期确实已正确设置 - 当您打开选择器时,这就是它登陆的日期,但当您登陆页面时它实际上并没有显示在显示字段中。在您实际选择一个值之前,它只是空白。

我尝试了很多不同的想法组合,但没有任何效果。这太令人沮丧了。我发现这个问题的变体/片段确实已经存在,但我找不到使用这种技术组合提出的问题的示例。在使用 NgbDatepicker 时,大多数人似乎依赖于模板化表单,而不是反应式表单。

cjd*_*187 6

startDatae日期选择器上的属性不设置初始值。您应该将 formControl 的值设置为您想要的值。

这是一个没有解析器的示例。我在工作中使用自定义解析器/格式化程序,但它确实有效(无法在此处发布该代码)。

工作 stackblitz(注意这是最新的 Angular 和 NgBootstrap)https://stackblitz.com/edit/angular-zpeul4

应用程序组件

  formGroup = new FormGroup({});

  ngOnInit() {
    console.log('on init');
    this.formGroup.addControl("test", new FormControl({day: 20, month:4, year:1969})) //nice
    this.formGroup.valueChanges.subscribe(val => {
      console.log(val);
    })
    console.log(this.formGroup.value);
  }
Run Code Online (Sandbox Code Playgroud)

模板

 <div class="container" [formGroup]="formGroup">
    
  <input #licenseExpiration="ngbDatepicker"
    class="form-control"
    [formControlName]="'test'"
    ngbDatepicker />

  <button class=""
  (click)="licenseExpiration.toggle()"
  type="button">open</button>

</div>  

Run Code Online (Sandbox Code Playgroud)

如果您的解析器仍然存在问题,请确保您同时具有NgbDateParserFormatterNgbDateAdapter,并且您设置的初始值可以由适配器正确转换(如果它不是 Ngb 日期对象)