TypeError: Cannot read properties of undefined (reading 'fan')

Viewed 281

This is a parent component template file. It is not giving any problem

app.component.html

<div>

  <input type="text" [(ngModel)]="electronics.light" name="light" placeholder="light">
  <input type="text" [(ngModel)]="electronics.fan" name="fan" placeholder="fan">
  

</div>
<button (click)="display();">Display</button>
<div *ngIf="flag">
  <app-electronics-layout [images]="images" [electronicsObj]="electronics"></app-electronics-layout>
</div>

This is some part of the child component ts file where the display1() method is called on button click to verify electronics fan value.

  @Input()
  electronicsObj!: electronics;

  display1(){
    console.log(this.electronics.fan);  //This is printing actual value input by user.
}

  myConfigurations:ElectronicsInterface = {
    fan: this.electronics.fan,     //this is giving TypeError
    light: this.electronics.light
  }

 


}
1 Answers

electronics is not defined when you try to access it, so you have this error.

To ensure you create your myConfigurations once the value is given by the parent, you can initialize it from a setter :

private _electronicsObj: electronics;

get electronicsObj() {
    return this._electronicsObj;
}

@Input() set electronicsObj(electronicsObj: electronics) {
    this._electronicsObj = electronicsObj;
    this.myConfigurations = {
        fan: electronicsObj.fan,
        light: electronicsObj.light
    }
}
Related