Angular passing array from parent to child component

26,191

Solution 1

You can make the array as input of children components.

@Component({
  selector: 'app-navigation',
  templateUrl: './navi.component.html',
  styleUrls: ['./navi.component.css']
})
export class NavigationComponent {
  @Input() masterArray : string[];
}

And pass the array to child component in html of parent component.

<app-navigation [masterArray]="masterArray"></app-navigation>

Solution 2

If the data needs to be accessed by multiple child components, you may want to instead create a service. The service can then hold the array and any component can access it.

I have a simple example here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  masterArray = ['Create', 'Foo', 'Bar']; 
}

Then you access that data like this:

import {Component} from '@angular/core';
import { DataService } from './data.service';

@Component({
   selector: 'app-navigation',
   templateUrl: './navi.component.html',
   styleUrls: ['./navi.component.css']
 })
 export class NavigationComponent {

 get masterArray() { 
    return this.dataService.masterArray; 
 } 

 constructor(public dataService: DataService) { } 
}
Share:
26,191
Alistair Hardy
Author by

Alistair Hardy

Updated on July 19, 2020

Comments

  • Alistair Hardy
    Alistair Hardy almost 4 years

    Before we start, I started learning Angular about 1 week ago, don't be afraid to take it right back to basics.

    So how do you do it? In app.component.ts I have an standard array that needs to be accessable by multiple child components.

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      masterArray = ['Create', 'Foo', 'Bar'];
    }
    

    How do pull this into child components generated by angular cli. For example I need to use it in the navigation component to generate the navigation panel.

    <li *ngFor = "let i of masterArray; let ind = index">
      <a>{{i}}</a>
    </li>