Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning.

So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by multiple child components.

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

How can we bring this into child components created by angular cli? For instance, I need to utilize it in the navigation component to form the navigation panel.

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

Answer №1

One way to utilize the array is by setting it as an input for child components.

@Component({
  selector: 'app-links',
  templateUrl: './links.component.html',
  styleUrls: ['./links.component.css']
})
export class LinksComponent {
  @Input() linkArray: string[];
}

To pass the array to a child component, include it in the parent component's HTML code.

<app-links [linkArray]="linkArray"></app-links>

Answer №2

To ensure that data can be accessed by multiple child components, consider creating a service instead. The service will hold the array, allowing any component to access it.

An example of this implementation can be found at:

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

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

You can then access the data in the following way:

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) { } 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

[Heroku][Angular] Dealing with "Template parse errors" upon deploying my application

Encountered errors while deploying my application using "express" on Heroku: Uncaught Error: Template parse errors: Unexpected closing tag "button". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR ...

Phaser 3 game app on iOS generated with Capacitor lacks audio functionality

I have developed a basic test app using Phaser 3 (written in Typescript and transpiled with rollup) and am utilizing Capacitor to convert it into an iOS application on my Mac. This excerpt highlights the key functionality of the app: function preload () { ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Angular2 is experiencing an unresolved peer dependency issue with ng2-bootstrap

While attempting to install ng2-bootstrap using npm, I encountered the following errors and warnings: https://i.stack.imgur.com/K7XjC.png Any suggestions on how to resolve this issue? ...

Troubleshooting Angular 2: Issues with http.delete() Function

deleteTask function in this code is currently experiencing issues. All other methods are functioning properly and the URL is also working correctly. Your assistance would be greatly appreciated. constructor(private http:Http) { console.log('task ...

Defining a custom type for accessing Date.getTime() in TypeScript

Are there any data types similar to Timestamp that could be utilized for Date().getTime() purposes? const currentTime = new Date().getTime(); ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

Using React Query's useMutation hook may result in an error message of "No overload matches this call"

When incorporating react-query into my typescript project, I encountered a perplexing type error while attempting to utilize the useMutation() hook with a graphql query. Here is an example of the code: useMutation( async ( parameter1: string, ...

Transferring information between two distinct components

I am facing an issue where I have a list of stores shown in an unordered list, and when this list is initialized the ngOnInit() function retrieves data for all the stores. However, I want to be able to send the store data from each list element to the stor ...

Facing a Timeout Issue while Testing an Angular application using Protractor

When working with an Angular application and setting browser.waitForAngularEnabled(true), I encountered the following error after clicking on an element: ScriptTimeoutError: script timeout (Session info: chrome=85.0.4183.121) Driver info: chromedriver=85.0 ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

Efficiently load Angular modules only when needed on different routes

My Angular project utilizes lazy loading for modules and below are the defined routes: { pathMatch: 'full', path: '', loadChildren: () => import('./pages/landing/home-page/home-page.module').then(m => m.Hom ...

The folder creation in the 'outDir' directory by TSC continues to grow

Hello! Currently, I am engaged in a small TypeScript project where I need to utilize two separate tsconfig.json files, both of which inherit from my main tsconfig.base.json file. Unfortunately, I encountered an issue with the compiler creating unnecessar ...