0

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 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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'];
}

1 Comment

Thanks, you are right, but still not working with this modification (I will update the question)
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.