Can you explain the distinction between using [ngFor] or [ngForOf] in Angular 2?

From what I gather, both serve the same purpose. However,


Am I correct in my understanding? Or can you provide more insight on the differences between ngFor and ngForOf?

Answer №1

The ngFor directive and the ngForOf directive may look like separate entities, but they are actually linked as selectors within the NgForOf directive.</p>

<p>If you dive into the <a href="https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts" rel="noreferrer">source code</a>, you'll find that the NgForOf directive is triggered by the presence of both <code>ngFor
and ngForOf attributes on an element.

When using *ngFor, the Angular compiler transforms this syntax into a standard form with both attributes present.

For example,

  <div *ngFor="let item of items"></div>

is de-sugared to:

 <template [ngFor]="let item of items">
     <div></div>
 </template>

This initial transformation is due to the '*', followed by another de-sugaring process for the micro syntax "let item of items". The Angular compiler converts it to:

 <template ngFor let-item="$implicit" [ngForOf]="items">
   <div>...</div>
 </template>

(Here, $implicit acts as an internal reference for the current item in the loop).

In its standardized form, the ngFor attribute serves as a marker, while the ngForOf attribute functions as an input supplying the list for iteration to the directive.

For more information, refer to the Angular microsyntax guide.

Answer №2

ngFor is a directive in Angular that serves as a replacement for the ng-repeat attribute found in AngularJS.

When using ngFor, you have the option to use it in a shorthand format:

<li *ngFor="let item of items">{{item.name}}</li>

Alternatively, you can use the longhand version like this:

<template ngFor let-item="$implicit" [ngForOf]="items">
  {{item.name}}
</template>

Answer №3

In my perspective, after going through the angular documentation,

  • [ngFor] is not type secure
  • [NgForOf] is type secure

This is due to the slight differences in the two class definitions

  • ngFor Class type is any type

  • However, ngForOf class type is generic ngForOf : NgIterable<T>


The use of generics in ngForOf aligns with what I mentioned earlier in my query.

Answer №4

NgFor is capable of iterating over an array, however in ngContainer and ngContent we cannot directly iterate using ngFor. Instead, we can utilize [ngForOf] for the iteration process. In this case, 'i' represents a variable, while 'ratings' represents an array.

Example:

 <ng-template ngFor let-i [ngForOf]="ratings">
                  <option *ngIf="i<=22" [ngValue]="i">{{i}}:00 Hrs.</option>
   </ng-template>

In this example, I have demonstrated how to apply both ngFor and ngIf simultaneously within the template.

An alternate scenario involves applying ngFor within a normal if statement, which results in conversion during rendering:

<template ngFor let-i [ngForOf]="ratings">
   <HTML Element>...</HTML Element>
 </template>

Answer №5

Clear version

  • (<template ngFor ...>) permits the application of the directive to many elements simultaneously

Underlying version

  • simply encloses the specific element it is applied to

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

What is the best way to bring in styles for a custom UI library in Angular 2?

In the realm of UI libraries, I find myself facing a dilemma. Upon importing SCSS styles into my components (such as a button), I noticed that if I instantiate the component button twice in the client app (which has my UI library as a dependency), the SCSS ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

Tips for populating array values in an Angular9 template using forms

.html page <pre> <div *ngFor="let data of data;let i=index" class="row_wrap"> <div class="row_inner_wrap"> <div class="row"> <div class="col-md-12"> <div class="col-md- ...

Angular has its own unique way of handling regular expressions through its TypeScript

Considering the creation of an enum to store various regex patterns in my application for enhanced code reuse. For example: export enum Regex { ONE_PATTERN = /^[example]+$/g, ANOTHER_PATTERN = /^[test]{5,7}$/g } However: Encountering the TS90 ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

Tips for obtaining a reference to the ngfor-list with a pipe implemented on it

When applying a filter to a list within an ngFor directive, such as *ngFor="data | pipe", it can be challenging to access the filtered data in the component class. One attempted solution is using *ngFor="data | pipe as filtereddata", but this approach seem ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Encountered a problem while trying to install angular-cli on a Windows 10

While attempting to set up angular-cli on my Windows 10 device, I used npm install -g @angular/cli. However, an error popped up as follows: C:\Users\kumar>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near &a ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

What is preventing Typescript from inferring the type when assigning the output of a method with a return type to a variable?

My reusable service has a public API with documentation and types to make client usage easier. interface Storable { setItem(key: string, value: string): any; getItem(key: string): string; removeItem(key: string): any; } @Injectable({ providedIn: & ...

Tips for binding data to numerous dynamic controls

Implementing reactive forms in my Angular project allowed me to create a simple form for adding employee work hours and breaks. The challenge I encountered was the inability to bind data from break controls. In the .ts file export class AddAppointmentForm ...

The installation of npm was unsuccessful due to an error in the postinstall script of the [email protected] package

Looking for help with my Angular application? Check it out on https://github.com/XBITSwitzerland/ngx-admin/tree/ng2-admin I'm trying to run: npm install Encountering the following error (excerpt from output): gyp ERR! build error gyp ERR! stack Er ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...

Unable to access or modify NGXS state within an Angular 8 NativeScript application

After gaining experience with Angular, I decided to experiment with the NGXS data store while following a NativeScript tutorial. Despite trying several NGXS tutorials, I couldn't get the state to update without any errors from Android Studio or NS. N ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Generic Typescript Placeholder Design

Imagine you have the following data: const dataA = { name: "John", age: 25, attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"}, } const dataB = { name: "Lisa", age: 38, attributes: {spe ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...