Search code examples
angulartypescriptangular5formbuilder

Angular patchValue not setting input field value


I am trying to set an input value via form group using patchValue() but the input still remains blank, this is my code sample...

component.html

<form [formGroup]="createStoreForm" (ngSubmit)="createStore()" novalidate>
  <label for="user">Unique User ID</label>
    <input type="text" name="user" class="form-control" [(ngModel)]="storeProfile.user" [formControl]="createStoreForm.controls['user']" readonly>
    <div *ngIf="createStoreForm.controls['user'].hasError('required') && formSubmitAttempt" class="form-error">Store user is required</div>
</form>

component.ts

export class storeProfileComponent implements OnInit {
  storeProfile: any = {};
  userData: any = {};
  userId: any;
  createStoreForm: FormGroup;
  formSubmitAttempt: boolean;

  constructor(fb: FormBuilder, private storeSrv: StoreService, private router: Router) {
    this.createStoreForm = fb.group({
      'user': ['', Validators.required],
    });
  }

  ngOnInit() {
    let tempUser = localStorage.getItem('user');
    if (tempUser) {
      this.userData = JSON.parse(tempUser);
      this.userId = this.userData.id;
    };

  this.createStoreForm.patchValue({
    'user': this.userId.id,  // this.userId.id = undefined here
  });
 }
}

What is the right way to pass value from localStorage to the input field on the form?


Solution

  • Just remove ngModel and use createStoreForm.value to get from values

    <form [formGroup]="createStoreForm" (ngSubmit)="createStore()" novalidate>
      <label for="user">Unique User ID</label>
        <input type="text" name="user" class="form-control" [formControl]="createStoreForm.controls['user']" readonly>
        <div *ngIf="createStoreForm.controls['user'].hasError('required') && formSubmitAttempt" class="form-error">Store user is required</div>
    </form>
    
    export class storeProfileComponent implements OnInit {
      storeProfile: any = {};
      userData: any = {};
      userId: any;
      createStoreForm: FormGroup;
      formSubmitAttempt: boolean;
    
      constructor(fb: FormBuilder, private storeSrv: StoreService, private router: Router) {
        this.createStoreForm = fb.group({
          'user': ['', Validators.required],
        });
      }
    
      ngOnInit() {
        let tempUser = localStorage.getItem('user');
        if (tempUser) {
          this.userData = JSON.parse(tempUser);
          this.userId = this.userData.id;
        };
    
      this.createStoreForm.patchValue({
        'user': this.userId.id,  
      });
     }
    
     public createStore(){
      console.log(this.createStoreForm.value); // get from values 
     }
    }