Usage of [ngForOf] in Angular Explained

One perspective is that applying ngFor during rendering converts it into a normal format. However, when adding ngFor to a div, it is important to note that while NgFor can iterate an array, it cannot be directly iterated in ngContainer or ngContent.

Question:

I am working on a project that includes the following code. Could you explain its purpose? While I am familiar with

*ngFor

and

*ngIf

, I am unsure about the functions of

[ngForOf]="topicdata"

and

ngFor let-topic

. Is there a more efficient way to simplify this code?

 
        
 

I would prefer it to be displayed in the manner depicted beneath.


But then it shows this error:

When using Angular, it is not possible to have more than one
template bindings
on a single element. Instead, you should either use a single
attribute named
‘template’, or prefix it with an asterisk (*) to avoid any conflicts.


Solution 1:

Angular refers to the

*ngFor

directive as microsyntax, which simplifies the configuration process for developers. The preceding

*

is an example of the microsyntax being used.

The code:

 

Will for example be equal to:


    ... 

As shown in the example mentioned in your question.

To put it briefly, by using

*ngFor="let topic of topicdata"

, you can substitute your code and achieve identical outcomes.

To address the issue, the *ngIf should be adjusted to appear on a different line instead of being on the same line.

When it comes to using structural directives in angular, it is important to note that using multiple of them on the same element is not permitted. To use

*ngIf

on the same line, it is recommended to loop out an

<ng-container>

element and place your

<topic>

within it.


    ... 

Additional information regarding

ng-container

can be found here.



Solution 2:


The ngFor syntax can be written differently using

let-topic [ngForOf]="topicdata"

. This syntax creates topic variables from the topicdata array. Alternatively, you can create the same syntax (with ng-template) by writing it as follows.

// some template

Additional information regarding this can be accessed at https://angular.io/guide/structural-directives#inside-ngfor.

Frequently Asked Questions