Search code examples
angulartypescriptangular6primengangular-ngmodel

cannot get [(ngModel)] value to use in component Angular 6


in html file, using ngModel which i want to get its value to use in my component

edit-customer.component.html

  <input id="userInfoEmail" type="text" class="form-control" value="{{userInfo.email}}" [(ngModel)]="userInfo.email" disabled>

since its two way binding, i had use it im my component as follows,

edit-customer.component.ts

checkUserEmail(): void {
    this.userInfo.email = this.userEmail;
    this.customerService.checkEmail(this.userEmail).subscribe((res) => {
        if (res.twoFactorEnabled === true) {
            this.isButtonDisabled = false;
        }
        else {
            this.isButtonDisabled = true;
        }
    })
}

also I had declared this.userEmail:string;, but unfortunately got error 'undefined' on my console, I read that i need to initialize the object but cant figure it out,


Solution

  • Do not use value with ngModel, remove it first,

      <input id="userInfoEmail" type="text" class="form-control" [(ngModel)]="userInfo.email" disabled>
    

    now you should be able to access the value in controller like,

    console.log(this.userInfo.email);
    

    whereas userInfo should be defiend at the top as,

    userInfo: any = {}; if you have a type change any with type