Search code examples
angularformsfirebase-realtime-databaseform-controlngmodel

Angular 5 ngModel setting default value based on form input


I have an app built in Angular 5 using Firebase's Real Time Database. My form is using ngModel and has a user id field and a custom username field. I need the username to have a default value of the user id unless the user chooses to change it.

<label class="label-control" for="idInput">User Name</label>
<input id="userId" type="text" for="idInput" class="form-control"
       required minlength="1" name="userId"
       [(ngModel)]="userData.userId"
       #userId="ngModel"
       placeholder="e.g. johnhancock1776"
       />

<label class="label-control" for="vanityInput">Your Custom URL</label>
<input id="vanityId" type="text"
       for="vanityInput" 
       class="form-control"
       name="vanityId"
       [(ngModel)]="userData.vanityId"
       value="{{userData.userId}}"
       #vanityId="ngModel"
       placeholder="custom url" />

When the user puts In their user id the vanity id field populates but won't send data to the database unless they add or delete something from the vanity field.

I tried adding:

       [ngModelOptions]="{updateOn: 'submit'}"

to the vanity field witch lets it send an empty string if neither field is touched, but won't send anything when only the user id is changed.


Solution

  • you could use a (ngModelChange) event to change the value of userData.vanityId instead of value="{{userData.userId}}" because you only change the view and not userData.vanityId value.

    component.html

    <label class="label-control" for="idInput">User Name</label>
    <input id="userId" type="text" for="idInput" class="form-control"
           required minlength="1" name="userId"
           [(ngModel)]="userData.userId"
           #userId="ngModel"
           placeholder="e.g. johnhancock1776"
           (ngModelChange)="changeVanityId($event)"
           />
    <br>
    <label class="label-control" for="vanityInput">Your Custom URL</label>
    <input id="vanityId" type="text"
           for="vanityInput" 
           class="form-control"
           name="vanityId"
           [(ngModel)]="userData.vanityId"
           #vanityId="ngModel"
           placeholder="custom url" />
    
    <button (click)="sendBackend()">Send</button>
    

    I added a button to print the userData value to verify that print the correct value.

    component.ts

      /**
       * Print in console
       */
      sendBackend() {
        console.log(this.userData);
      } 
    
      /**
       * Change value of vanityId
       */
      changeVanityId(event) {
        this.userData.vanityId = event
      }
    

    I implement this here: https://stackblitz.com/edit/angular-sadk7e