Angular 9, Binding an array as an @Input for child component is not working

3k Views Asked by At

For some reason, the array is not passed to the child components. What I'm missing?

My child component: .html

<ul>
    <li *ngFor="let item of items">
        <a (click)="itemHasBeenClicked(item)">{{item}}</a>
    </li> 
<ul>

.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';


@Component({
  selector: 'app-three-dots-menu',
  templateUrl: './three-dots-menu.component.html',
  styleUrls: ['./three-dots-menu.component.sass']
})
export class ThreeDotsMenuComponent implements OnInit {

  constructor() { }

  @Input()
  public itemsList : string[];

  ngOnInit(): void {

  }

  @Output()
  itemClicked: EventEmitter<string> = new EventEmitter<string>();

  itemHasBeenClicked(item)
  {
    alert(item);
    this.itemClicked.emit(item);
  }
}

parent component: .html

<app-three-dots-menu  [itemsList]="menuItems"></app-three-dots-menu>

.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-users-table',
  templateUrl: './users-table.component.html',
  styleUrls: ['./users-table.component.sass']
})
export class UsersTableComponent implements OnInit {

  constructor() { }
  menuItems : string[] = ['New User', 'Refresh'];

  ngOnInit(): void {  

  }



}

if I initialize the itemsList of the child component (ThreeDotsMenuComponent) in the ngOnInit it works and shows properly. any other option is not working, include this line

@Input()
  public itemsList : ["item1","Item2"];

I'm sure I'm missing a small thing somewhere, I already followed many instructions and read many posts here and in other forums, and still stuck.

3

There are 3 best solutions below

0
Abhishek On BEST ANSWER

In the child template html you are referring to items instead of itemsList

Change the child template to:

<ul>
    <li *ngFor="let item of itemsList">
        <a (click)="itemHasBeenClicked(item)">{{item}}</a>
    </li> 
<ul>

Have a look at the following: https://stackblitz.com/edit/angular-v8sk5f?file=src%2Fapp%2Fchild%2Fchild.component.html

1
Poul Kruijt On

Well, you have to use = and not :. With the : you are defining the type of the property, not the actual value:

export class UsersTableComponent implements OnInit {
  menuItems: string[] = ['New User', 'Refresh'];
}
0
mario89 On

In ThreeDotsMenuComponent html part, you are reffering to items, but you need use itemsList

<ul>
    <li *ngFor="let item of items"> <!-- here, use itemsList -->
        <a (click)="itemHasBeenClicked(item)">{{item}}</a>
    </li> 
<ul>