Search code examples
angularangular4-forms

how to sync 2 value of 2 String Interpolation to one Input ngModel angular 6


In html code must be 3 ngModel for 4 values that one of them are combination of two values, how can bind two value to one ngModel?

          <span class="user">{{userInfo.FirstName}} {{userInfo.LastName}}</span>
          <span class="user">{{userInfo.Mobile}}</span>
          <span class="user">{{userInfo.Email}}</span>

          <input [(ngModel)]='userInfo.FirstName userInfo.LastName' />
          <input [(ngModel)]='userInfo.Mobile' />
          <input [(ngModel)]='userInfo.Email' />

ts:

  userInfo = {
     FirstName: 'x',
     LastName: 'y',
     Mobile: '09999999999',
     Email: 'x@gmail.com'
  };

Solution

  • You could use a property and do the join/split in the getter/setter like this: https://stackblitz.com/edit/angular-ytfbsn?file=src%2Fapp%2Fapp.component.ts

    get firstAndLastName() {
      return this.userInfo.FirstName + (this.userInfo.LastName ? ' ' + this.userInfo.LastName : '');
    }
    set firstAndLastName(value: string) {
      const parts = value.split(' ');
      this.userInfo.FirstName = parts[0] || '';
      this.userInfo.LastName = parts.slice(1).join(' ');
    }