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>
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>
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) { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With