5

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>
3
  • Possible duplicate of Angular 2 pass data parent to child component Jul 18, 2017 at 16:20
  • 1
    My suggestion: whenever you have a question, google around and read more before creating something in SO. This is a really basic topic, and directly asking as u did is from my point of view lack of research capabilities Jul 18, 2017 at 16:21
  • 1
    I'd been googling and had read multiple threads on SO, even the one linked by yourself. However I either couldn't get them to work or they were not relevant to what I'm doing Jul 19, 2017 at 8:59

2 Answers 2

10

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>
1
  • Thank you! I'm new to Angular, also. The HTML was what I was missing in every other answer. Jul 5, 2019 at 3:26
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) { } 
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.