Is it better to use *ngFor in the parent component or the child component in Angular

I've created an app-wall template and I'm seeking advice on whether to use

<app-brick *ngFor="..."></app-brick>
or a <app-bricks> element with an *ngFor inside its own template. Is there a recommended best practice for this scenario, or does it vary depending on the specific case?

@Component({
  selector: 'app-wall',
  template: `
      <app-brick *ngFor="let brick of bricks"></app-brick>

      or

      <app-bricks></app-bricks>
  `
})
@Component({
  selector: 'app-brick',
  template: '<div> I'm a brick! </div>'
})
@Component({
  selector: 'app-bricks',
  template: '<div *ngFor="let brick of bricks"> I'm a brick! </div>'
})

Answer №1

In my opinion, it is preferable to pass the bricks array to the child component and display it as '

<div *ngFor="let brick of bricks"> I'm a brick! </div>'
because it ensures that the child component will only be rendered once.

parent.ts

<app-bricks [bricks]="bricks"></app-bricks>

child.ts

@Input() bricks : any[]

@Component({
  selector: 'app-bricks',
  template: '<div *ngFor="let brick of bricks"> I'm a brick! </div>'
})

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

Effective method. Organizing directories and documents in Angular

Is there a resource available that provides a comprehensive example project demonstrating best practices for Angular? I am particularly interested in understanding the recommended file structure and directory organization for developing with Angular. ...

Issues with Cross-Origin Resource Sharing (CORS) have been identified on the latest versions of Android in Ionic Cordova. However, this problem does not

I am encountering an issue with my TypeScript Ionic code. It works well in browsers and some older mobile devices, but it fails to function on newer Android versions like 8+. I need assistance in resolving this problem. import { Injectable } from '@an ...

Angular and RxJS: Ensuring continuous interval execution in the event of an error

Every 10 seconds, I make a call to a RESTful service through an Angular service called "myservice" and a function called "foo." ngOnInit () { interval (10000).pipe (startWith (0), mergeMap (obs => this.myservice.foo ())).subscribe (resp = ...

I am having trouble accessing the value from an Angular 2 service outside of the subscribe function

Within my component, there is a save function that looks like this: save() { var result; //For updating task if (this.task.AllTaskId) { if (this.task.AssignedToCode == null) { this.task.AssignedToCode = "All"; } ...

Issue concerning the Bootstrap version, transitioning from Bootstrap 3 to Bootstrap 4

Upon initially installing bootstrap version "bootstrap": "^3.3.7",, everything was functioning properly, except for the inability to utilize a card component. For example: <div class="card" style="width: 18rem;"> <img class="card-img-top" src= ...

Query a Firestore collection in Angular 6 with AngularFire by specifying multiple document fields

In my current project, I am utilizing AngularFire and Cloud Firestore. I encountered an issue where I need to implement a query with multiple conditions (where) to target a specific collection. Upon attempting to write the code for this query, I realized ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Show the monetary value in the appropriate currency format, including fractions if the currency supports them

Here is the code snippet I am using to display the amount: <td>{{transaction.amount}} {{transaction.currency}}</td> Currently, the output looks like: 56030 USD I would like the output to be formatted like this: <td [ngSwitch]="transacti ...

Using two separate ngModel directives in a parent component to control individual child component elements

One of the challenges I am facing is how to handle a child component with 2 input text-fields simultaneously. Both of these fields require ngModel validation in the parent component. Additionally, both inputs are mandatory and need to be checked using !for ...

The type 'FirebaseAuth' cannot be assigned to type 'Auth'

Recently, after updating my project dependencies, I encountered the following error: ERROR in src/app/services/auth/auth.service.ts(19,5): error TS2322: Type 'FirebaseAuth' is not assignable to type 'Auth'. Types of property &a ...

Working with Array of Objects Within Another Array in Angular 6 Using Typescript

I'm currently working with an array of "food": "food": [ { "id": 11, "name": "Kabeljaufilet", "preis": 3.55, "art": "mit Fisch" }, { "id": 12, "name": "Spaghetti Bolognese", "preis": 3.85, "art": "mit Fleisch" }, { "id": 1 ...

Ionic 3 is unable to find a provider for CallNumber

Recently, I have been working with Ionic 3 and encountered an issue when trying to call a number using the Call Number plugin. Here are the steps I followed to add the plugin: ionic cordova plugin add call-number npm install --save @ionic-native/call-numb ...

Error message: "Reading properties of undefined in Angular unit test"

I'm currently working on unit testing a component where both the component and page are importing from @bloomreach/spa-sdk. export class ThinComponent implements OnInit { @Input() component!: BrComponent; componentModels: any; page: Page; ...

What is the Placement of Grant_Type in XHR?

I attempted to access my OAuth2 Token through an XHR-Request in TypeScript, but I consistently receive a 400 error with the message: {"error":"unsupported_grant_type","error_description":"Grant Type is NULL"} The request is being made from a NativeScript ...

Retrieve a specific attribute from an HTTP Observable result

Calling all RxJS experts, I have a question for you. Currently working with Angular 5. Here's what I am trying to accomplish: this.allFilters = this.http.get(path).pipe( map((response) => response.forms.sim_filter.schema.properties)) The ...

Change typescript so that it shows "require" instead of "import" when outputting

Currently, I am converting TypeScript code to JavaScript for an application that is specifically targeting Node v.14. My goal is to have the output contain require statements instead of import statements. This is what my configuration file looks like: { ...

Create a Typescript function that takes in a Class as a parameter

My goal is to create a function that can switch based on the name of a class definition passed in as a parameter. This function will simplify my testing process by allowing me to generate data for different classes using just one function. generateMockDat ...

The lifecycle of Angular 7 when the entire page has finished loading, the data has been bound, and the rendering

I'm currently working on monitoring any modifications to the data in this page. My approach has been as follows:   1. I have a variable called dataChanged    2. I set it to false once the page has finished loading    3. I update it to true whene ...

Can one specify a conditional return type in TypeScript without resorting to typecasting within the function's implementation?

I'm currently working on a function where the return type is determined by the input values, but I'm finding that typescript is requiring me to use the as keyword to address the issue I'm facing. Is there a more graceful way to handle this a ...

What is the proper way to categorize a "type as a subclass of a class"?

class SuperClass { ... } class SubClass1 extends SuperClass { ... } class SubClass2 extends SuperClass { ... } class SubClass3 extends SuperClass { ... } const foo: ??? = ... Is there a way to assign a type to foo indicating that it is an instance of an ...