Setting Default Values in an Angular Reactive Form

Something I ran into a few months back was that Angular won't reset a FormControl back to its initial value if you call reset() on the FormGroup unless that FormControl was created with nonNullable: true. Here's an example:

  private createForms(formBuilder: FormBuilder): void {
    //For the initial values to be considered the *default* values, we need to specify nonNullable: true.
    //There used to be a dedicated property for this, but they deprecated it.
    this.searchForm = formBuilder.group<ISearchForm>({
      adminYear: new FormControl<number>(null, { validators: Validators.required }),
      admin: new FormControl<string>('All', { nonNullable: true, validators: Validators.required }), //Validator is kind of pointless here, as there WILL always be a value
      examName: new FormControl<string | null>(null),
      dateApproved: new FormControl<string>('Both', { nonNullable: true }),
      status: new FormControl<string>('Draft', { nonNullable: true })
    });

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

Silent Renew and the "login_required" Error When Using oidc-client