Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular passing array from parent to child component

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>
like image 762
Alistair Hardy Avatar asked Jul 18 '17 15:07

Alistair Hardy


2 Answers

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>
like image 186
subaru710 Avatar answered Oct 08 '22 10:10

subaru710


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) { } 
}
like image 28
DeborahK Avatar answered Oct 08 '22 11:10

DeborahK