Home > OS >  IS the syntax to pass the index element from an array wrong in Angular
IS the syntax to pass the index element from an array wrong in Angular

Time:08-12

I am trying to show the filenames from an array into UI. Below is my Angular code:

 <div *ngFor="let file of myFiles">
      **{{ file.name }}**
 </div>

The code for AppComponent is:

export class AppComponent {
  public myFiles: Array<{ [key: string]: string | number }> = [
    { name: "First.txt", size: 500 },
    { name: "Second.jpg", size: 100 }
  ];

  public clearModel(): void {
    this.myFiles = [];
  }
}

I want to display the name parameter from my Array on the list. I get the error:"Property 'name' comes from an index signature, so it must be accessed with ['name'].ngtsc(4111)"

I have tried {{file[name]}} which returns error: Property 'name' does not exist on type 'AppComponent'

CodePudding user response:

You should pass a string: file['name'].

Or you can disable this check in tsconfig.json:

"compilerOptions": {
  "noPropertyAccessFromIndexSignature": false
}
  • Related