Error in ngModel call

Asked

Viewed 85 times

0

I’m making a mistake of ' Cannot read Property 'razao_social' of Undefined' when I call an ngModel in my html.

I created an interface like this:

export interface IEmpresas {
  nome_fantasia : string;
  razao_social : string;
  cnpj : string;
}

In my component, I installed the interface and created a variable with the type of my interface.

...
private empresa : IEmpresas;
...

and then, I call ngModel in html

<input type="text" [(ngModel)]="empresa.razao_social" id="razao_social">

2 answers

1

The company variable is starting as Undefined, or null.

You declare it with the safe operator ( company?.razao_social). This should solve, although it is not the ideal solution.

  • I understand. and in this case what would be the ideal solution?

  • The ideal solution may depend on some factors. Does it make sense that the enterprise variable is empty ? Would this be a failure to request the backend ? This variable will be loaded later when the Promise receives its result ? . But you can simply initialize this variable with an empty object in your controller or just use the same safe navigation operator (?). The result will be very similar and it is a good solution, in my opinion.

0


To start the object with an empty value

private empresa : IEmpresas = {
  nome_fantasia : '';
  razao_social : '';
  cnpj : '';
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.