Search code examples
angularangular-formsangular-validation

Why the binding is not working properly when using the "required" attribute?


I have the following HTML code in an Angular component that is been invoked to displayed a record details:

<div class="form-group">
    <label for="date1">Date 1 *</label>
    <div class="input-group">
      <input 
          class="form-control" 
          placeholder="yyyy-mm-dd" 
          id="date1" 
          name="date1"
          [ngModel]="date1"
          required
          #date1=ngModel
          [class.field-error]="form.submitted && date1.invalid"
          ngbDatepicker #da2="ngbDatepicker" 
          tabindex="13">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary calendar" (click)="da2.toggle()" type="button"></button>
      </div>
    </div>
</div>

As you can see, this is a input control that is displaying a date value in the format of yyyy-MM-dd.

The variable date1 that is used on the ngModel is in a JSON format: { year: 1999, month: 01, day: 01}.

So, when the component is being rendered this particular control is not displaying the binding value on the date1 variable. However, if I removed the required attribute the value is displayed.

Does anyone know how to achieved both of this functionalities? Displaying the date value without removing the required attribute?


Solution

  • Cause

    The input is not displaying the binding value because it has id and name set to date1 and the variable is named date1 as well.

    Solution

    Rename the variable of type NgbDateStruct used in [ngModel]="date1" to something else, e.g. myDate.

    Example

    ts:

    myDate: NgbDateStruct = { year: 1969, month: 11, day: 2 };
    

    html:

    <div class="form-group">
        <label for="date1">Date 1 *</label>
        <div class="input-group">
            <input 
            class="form-control" 
            placeholder="yyyy-mm-dd" 
            id="date1" 
            name="date1"
            [ngModel]="myDate"
            required
            #date1=ngModel
            ngbDatepicker #da2="ngbDatepicker" 
            tabindex="13">
            <div class="input-group-append">
                <button class="btn btn-outline-secondary calendar" (click)="da2.toggle()" type="button"></button>
            </div>
        </div>
    </div>
    

    Result

    input displaying date