user11352561
user11352561

Reputation: 2647

Angular - Object is possibly 'undefined' in Angular PatchValue Update

I am implementing PatchValue for update in Angular-12.

API JSON Response:

"message": "Student Detail.",
"error": false,
"code": 200,
"results": {
    "student": {
        "id": 4,
        "first_name": "ALEX",
        "last_name": "KOY",
        "activity": [
            {
                "id": 1,
                "student_id": 1,
                "activity_name": "Swimming",
               "activitytype": {
                    "id": 1,
                    "type_name": "Compulsory",
               }  
            }
        ],
    }
}

From the above, a student gets involved in one activity name

interface:

export class StudentResponse {
 results!: { student: IStudent;};
}

export interface IStudent {
  id?: number;
  first_name: string;
  last_name: string;
  activity?: IActivity[];
}

export interface IActivity {
  id?: number;
  type_id? number; 
  activitytype?: {id:number,type_name:string};
  activity_name: string;
}

service:

getStudentById(id: number): Observable<StudentResponse> {
  return this.http.get<StudentResponse>(this.api.baseURL + 'students/fetchbyid/' + id, this.httpOptions);
}

component:

ngOnInit(): void {
  this._id = this.route.snapshot.params['id'];
  this.updateStudent();
  this.loadStudentById();
}

updateStudent(){
  this.studentForm  = this.fb.group({
    id: [''],
    first_name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
    last_name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
    activity_name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
    type_id: [''],
  });
 }

 get fp(){ return this.studentForm.controls; };

loadStudentById() {
 this.studentService.getStudentById(this._id)
 .subscribe(
  (data: StudentResponse) => {
    this.student = data.results.student;
    this.studentForm.patchValue({
      first_name: this.student.first_name,
      last_name: this.student.last_name,
      activity_name: this.student.activity[0]?.activity_name,
    });
  }
 );
}

HTML:

<div *ngIf="student != undefined">
  <div class="col-12 col-md-4">
    <div class="form-group">
      <label for="first_name">First Name:<span style="color:red;">*</span></label>
      <input type="text" formControlName="first_name" placeholder="First Name" class="form-control" required/>
    </div>
    <div *ngIf="fp.first_name.touched && fp.first_name.invalid">
      <div *ngIf="fp.first_name.hasError('required')">
        <div class="text-danger">
          First Name is required!
        </div>
      </div>
      <div *ngIf="fp.first_name.hasError('minlength')">
        <div class="text-danger">
          First Name cannot be less than 2 characters!
        </div>
      </div>
      <div *ngIf="fp.first_name.hasError('maxlength')">
        <div class="text-danger">
          First Name cannot be more than 50 characters!
        </div>
      </div>
    </div>
  </div>
  <div class="col-12 col-md-4">
    <div class="form-group">
      <label for="last_name">Last Name:<span style="color:red;">*</span></label>
      <input type="text" formControlName="last_name" placeholder="Last Name" class="form-control" required/>
    </div>
    <div *ngIf="fp.last_name.touched && fp.last_name.invalid">
      <div *ngIf="fp.last_name.hasError('required')">
        <div class="text-danger">
          Last Name is required!
        </div>
      </div>
      <div *ngIf="fp.last_name.hasError('minlength')">
        <div class="text-danger">
          Last Name cannot be less than 2 characters!
        </div>
      </div>
      <div *ngIf="fp.last_name.hasError('maxlength')">
        <div class="text-danger">
          Last Name cannot be more than 50 characters!
        </div>
      </div>
    </div>
  </div>
  <div class="col-12 col-md-4">
    <div class="form-group">
      <label for="activity_name">Activity Name:<span style="color:red;">*</span></label>
      <input type="text" formControlName="activity_name" placeholder="Last Name" class="form-control" required/>
    </div>
  </div>
</div>

console.log(this.student)

gives:

Object
 id: 4
 alex_name: "ALEX"
 last_name: "ROY"
 activity: Array(1)
  0:
   id: 1
   type_id: 1
   activitytype: {id: 1, type_name: "Compulsory", …}
   activity_name: "Swimming"

This is to first retreive the data before I eventually submit to update records

I got this error in the component:

Object is possibly 'undefined

(property) IStudent.activity?: IActivity[] | undefined

this is highlighted:

this.student.activity[]

How do I resolve this?

Thanks

Upvotes: 0

Views: 320

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19108

The warning is correct.

On the line that you make

.subscribe(
  (data: StudentResponse) => {
    this.student = data.results.student;
    this.studentForm.patchValue({
      first_name: this.student.first_name,
      last_name: this.student.last_name,
      activity_name: this.student.activity[].activity_name, <--------------
    });
  }
 );

this.student.activity[] Is not a specific activity object.

this.student.activity[0], this.student.activity[1], this.student.activity[2] could be specific activity objects which could be used.

The form model that you use though does not seem to be correct. There should be an array of activities in your form each one holding an activity_name

Upvotes: 1

Related Questions