Monomoni
Monomoni

Reputation: 435

Angular form not taking in initial value

In the form i've created, the input would be preset to the value from {{userPrivate.email}}

and it is showing on the form but when I try to submit without amendment it shows that the value within it is empty unless I try to change it.

I want to make it such that even with the field unchanged, I can still submit it with the value of userPrivate.email

here's the html

<div class="card">
  <div *ngIf="(user$ | async) as user" class="card-body">
    <div class="row" *ngIf="(userPrivate$ | async) as userPrivate">
      <form (ngSubmit)="this.updateEmail(password.value, email.value)" class="container" [formGroup]="changeEmail">
        <mat-form-field>
         <input matInput type="text" placeholder="New Email" formControlName="email" value="{{userPrivate.email}}" >
        </mat-form-field>
        <button mat-raised-button type="button" class="mb-3" (click)="verifyEmail()"  *ngIf="!userEmail">
          <span *ngIf="!loading">Update Email</span>
          <i class="fa fa-spinner fa-spin" *ngIf="loading"></i>
        </button>
        <mat-form-field *ngIf="userEmail">
          <input matInput type="text" placeholder="Password" formControlName="password"  >
        </mat-form-field>
        <button mat-raised-button type="submit" class="mb-3" *ngIf="userEmail">
          <span *ngIf="!loading">Confirm</span>
          <i class="fa fa-spinner fa-spin" *ngIf="loading"></i>
        </button>
      </form>
    </div>
  </div>
</div>

and the function i'm calling in ts

ngOnInit() {

  this.changeEmail = this.fb.group({
    email: ['', [
      Validators.required,
      Validators.email
    ]],
    password: ['',
      Validators.required
    ]
  });
}
// Use getters for cleaner HTML code
get email() { return this.changeEmail.get('email')}
get password() { return this.changeEmail.get('password')}
verifyEmail() {
  this.userEmail = true;
}
updateEmail(password, email) {
  this.loading = true;
  debounceTime(300);
  this.authService.changeEmail(password, email).then(() => {
    this.loading = false;
    this.userEmail = false;
  });
}

Upvotes: 1

Views: 1260

Answers (2)

Mustafa Kunwa
Mustafa Kunwa

Reputation: 867

Pass your value while Creating form or By setValue/patchValue

 ngOnInit() {    
      this.changeEmail = this.fb.group({
        email: [userPrivate.email, [
          Validators.required,
          Validators.email
        ]],
        password: ['',
          Validators.required
        ]
      });
    }

Upvotes: 1

Michał Tkaczyk
Michał Tkaczyk

Reputation: 736

You're assigning empty value to controls on init

email: ['', [
  Validators.required,
  Validators.email
]],

Try to provide data to first argument in controls when you create form

Upvotes: 2

Related Questions