Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - "Cannot read property of undefined"

Tags:

angular

In Angular 5, for input

<input name="techSpecMeta.make" [(ngModel)]="techSpecMeta.make" type="text" class="form-control border-input" placeholder="Enter car brand">

getting error Cannot read property 'make' of undefined at Object.eval [as updateDirectives]

export class UserComponent implements OnInit {
  constructor(private vahinfo: VehicleInfo) {}
  ngOnInit() {}
  techSpecMeta: {};
  onSave = function(vehicle, isValid: boolean) {
    this.vahinfo.saveVehicle(vehicle).subscribe(data => {
      console.log(data.data)
    }, error => this.errorMessage = error)
  }
}
like image 521
jinks Avatar asked Feb 02 '18 06:02

jinks


People also ask

How do you fix undefined property Cannot be read?

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.

Can not read the property of undefined typescript?

What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.

Can not read the property of undefined Reading 0?

The "Cannot read property '0' of undefined" error occurs when trying to access the 0th index in a variable that stores an undefined value. Make sure to initialize the variable to the correct type, e.g. array or string, before accessing the index.

How do you fix TypeError Cannot read properties of null?

To solve the "Cannot read property 'value' of null" error, make sure you aren't accessing the value property on a null value, e.g. a non-existent DOM element. An element with the provided id does not exist in the DOM, so the getElementById method returns null .


2 Answers

techSpecMeta: {};

In Type script this means to declare a property of type {} with no value initialized. It is the same as:

techSpecMeta: Object;

You should instead be doing

techSpecMeta = {};

To make the binding work, you will need the property make as well.

techSpecMeta = {make: null};

Ideally you would create a class/interface for TechSpecMeta

class TechSpecMeta {
    make: null;
    anotherProperty: null;
}

and use it in your component

techSpecMeta = new TechSpecMeta();
like image 145
sabithpocker Avatar answered Oct 23 '22 11:10

sabithpocker


please try to intialize it as below description

public techSpecMeta = <any> {};

like image 22
Bhavin Patel Avatar answered Oct 23 '22 12:10

Bhavin Patel