Question how to add object to an Array in Angular

Asked

Viewed 23 times

0

I am learning Angular and am creating a method that will add an object in an Array to view in html using the Ngfor directive.

The error is in the part that functio.push({})

export class AppComponent {
  UltimoId = 0;
  nome = "";
  adicionado = false
  funcionarios : string[] = [];

  adiciona(){
  console.log(`Adicionado ${this.nome}`)
  this.adicionado = true;
  this.funcionarios.push({
    nome : this.nome,
    id : ++this.UltimoId
  });
}

My Mistake

Error: src/app/app.component.ts:21:26 - error TS2345: Argument of type '{ nome: string; id: number; }' is not assignable to parameter of type 'string'.

21 



this.funcionarios.push({
                            ~
22     nome : this.nome,
   ~~~~~~~~~~~~~~~~~~~~~
23     id : ++this.UltimoId
   ~~~~~~~~~~~~~~~~~~~~~~~~
24   });
   ~~~
  • funcionarios : string[] = []; functios has to be an array of strings, so if you try to push an object, it will give error. In this case, create an interface for this object and assign it to employees. Example: funcionarios : FuncObject[] = [];, or use the any (unsaved): funcionarios : any[] = [];

  • Create an interface for this object. Ex: interface FuncObject {
 id: number;
 nome: string;
} and use in funcionarios : FuncObject[] = [];

  • All right! Thanks a lot.

No answers

Browser other questions tagged

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