Home > Enterprise >  VM500:1 ERROR TypeError: Cannot read properties of undefined (reading 'controls') on Angul
VM500:1 ERROR TypeError: Cannot read properties of undefined (reading 'controls') on Angul

Time:01-07

My system is working fine but this error keeps showing I don't know what is the problem. Please help.

Here is my add.component.html

<form
  [formGroup]="userValue"
  
>
  <div >
    <h5  id="registerTitle">
      User Registration
    </h5>
    <div >
      <label for="txtName" >Name</label>
      <input
        type="text"
        formControlName="name"
        
        id="txtName"
        placeholder="Enter your name."
      />
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['name'].dirty ||
            userValue.controls['name'].touched) &&
          userValue.hasError('required', 'name')
        "
        >Input required</span
      >
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['name'].dirty ||
            userValue.controls['name'].touched) &&
          userValue.hasError('minlength', 'name')
        "
        >Input must have minimum length of 3 characters</span
      >
    </div>
    <div >
      <label for="txtEmail" >Email</label>
      <input
        type="email"
        formControlName="email"
        
        id="txtEmail"
        placeholder="Enter your email."
      />
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['email'].dirty ||
            userValue.controls['email'].touched) &&
          userValue.hasError('required', 'email')
        "
        >Input required</span
      >
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['email'].dirty ||
            userValue.controls['email'].touched) &&
          userValue.hasError('email', 'email')
        "
        >Valid email is required</span
      >
    </div>
    <div >
      <label for="txtPhone" >Phone</label>
      <input
        type="text"
        formControlName="phone"
        
        id="txtPhone"
        placeholder="Enter your phone number. ex. 09221111333"
      />
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['phone'].dirty ||
            userValue.controls['phone'].touched) &&
          userValue.hasError('required', 'phone')
        "
        >Input required</span
      >
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['phone'].dirty ||
            userValue.controls['phone'].touched) &&
          userValue.hasError('maxlength', 'phone')
        "
        >Input must have maximum length of 11 characters</span
      >
      <span
        style="color: red"
        *ngIf="
          (userValue.controls['phone'].dirty ||
            userValue.controls['phone'].touched) &&
          userValue.hasError('minlength', 'phone')
        "
        >Input must have minimum length of 11 characters</span
      >
    </div>
  </div>
  <div >
    <button
      type="button"
      [disabled]="!userValue.valid"
      *ngIf="btnShowSubmit"
      (click)="addUser()"
      
    >
      Submit
    </button>
    <button
      type="button"
      *ngIf="btnShowUpdate"
      (click)="updateUser()"
      
    >
      Update
    </button>
  </div>
</form>

Here is my .ts page

import {
  Component,
  OnInit,
  Input,
  EventEmitter,
  Output,
  SimpleChanges,
  OnChanges,
} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
} from '@angular/forms';
import { ApiService } from '../service/api.service';
import { userModel } from '../models/model';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
})
export class AddComponent implements OnInit, OnChanges {
  userValue!: FormGroup;
  userModelObj: userModel = new userModel();
  userList: any = [];
  btnShowSubmit = true;
  btnShowUpdate = false;
  @Input() userInfo: userModel = {
    id: 0,
    name: '',
    email: '',
    phone: '',
  };

  @Output() addlist = new EventEmitter();
  @Output() updatelist = new EventEmitter();

  constructor(private formbuilder: FormBuilder, private api: ApiService) {}

  ngOnInit(): void {
    this.userValue = this.formbuilder.group({
      name: new FormControl('', [Validators.required, Validators.minLength(3)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      phone: new FormControl('', [
        Validators.required,
        Validators.minLength(11),
      ]),
    });
    this.getUser();
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.editUser(this.userInfo);
  }

  addUser() {
    this.userModelObj.name = this.userValue.value.name;
    this.userModelObj.email = this.userValue.value.email;
    this.userModelObj.phone = this.userValue.value.phone;
    this.api.postUser(this.userModelObj).subscribe({
      next: (v) => {
        console.log(v);
        console.log('User added');
        this.addlist.emit(v);
        alert('User record added');
        this.getUser();
        this.userValue.reset();
      },
      error: (e) => {
        console.log(e);
        alert('Error');
      },
      complete: () => {},
    });
  }

  getUser() {
    this.api.getUser().subscribe((res) => {
      this.userList = res;
    });
  }

  deleteUser(data: any) {
    this.api.deleteUser(data.id).subscribe({
      next: (v) => {
        console.log(v);
      },
      error: (e) => {
        console.log(e);
        alert('Error');
      },
      complete: () => {
        console.log('User deleted!');
        alert('User record deleted');
        this.getUser();
        this.userValue.reset();
      },
    });
  }

  editUser(data: any) {
    this.userValue.controls['name'].setValue(this.userInfo?.name);
    this.userValue.controls['email'].setValue(this.userInfo?.email);
    this.userValue.controls['phone'].setValue(this.userInfo?.phone);
    this.userModelObj.id = this.userInfo.id;
    this.showUpdate();
  }

  updateUser() {
    this.userModelObj.name = this.userValue.value.name;
    this.userModelObj.email = this.userValue.value.email;
    this.userModelObj.phone = this.userValue.value.phone;
    this.api.putUser(this.userModelObj, this.userModelObj.id).subscribe({
      next: (v) => {
        alert('User has been updated');
        this.updatelist.emit(v);
        this.getUser();
        this.userValue.reset();
        this.showSave();
        this.userModelObj.id = 0;
      },
      error: (e) => {
        console.log(e);
        alert('Error');
      },
      complete: () => {
        console.log('complete');
      },
    });
  }

  showSave() {
    this.btnShowSubmit = true;
    this.btnShowUpdate = false;
  }

  showUpdate() {
    this.btnShowSubmit = false;
    this.btnShowUpdate = true;
  }
}

Here is the error

Feel free to check for further information

  1. I don't get to understand the error
  2. I tried replacing this.userValue = this.formbuilder.group with this.userValue = new FormControl but the error is still existing.
  3. I am a newbie on programming please help. Thank you :)

CodePudding user response:

It's look like your editUser() doesn't found controls property, So that's why you are getting this error.

Your editUser() function should look like below:

editUser(data: any) {
      this.userValue.controls.name.setValue(this.userInfo?.name);
      this.userValue.controls.email.setValue(this.userInfo?.email);
      this.userValue.controls.phone.setValue(this.userInfo?.phone);
      this.userModelObj.id = this.userInfo.id;
      this.showUpdate();
}

CodePudding user response:

In the template use userValue?.controls instead of userValue.controls. Hope this will help you.

  • Related