Strange gap when using <template ngFor> instead of *ngFor

Issue

lets the follow codes:

<template ngFor [ngForOf]="items" let-item>
            <li>
                <a class='dnp1-menu-link' [routerLink]="[item.route]">
                    <span>{{item.label}}</span>
                </a>
            </li>
</template>

And:

<li *ngFor="let item of items">
        <a class='dnp1-menu-link {{ item.domClass }}' [routerLink]="[item.route]">
            <span> {{item.label}} </span>
        </a>
</li>

I’ve assumed this two snippets would result in same behaviour, but:

The first snippet result:The first snippet result

and the second one:The second one.

Is this expected? Why?

I’ve realize the reason was “\n” between template and follow tag
E.g, this works:

<template ngFor [ngForOf]="items" let-item><li>
    <a class='dnp1-menu-link' [routerLink]="[item.route]">
        <span>{{item.label}}</span>
    </a>
</li></template>

Still, I don’t understand why and don’t know if this is a bug or feature.

Solution

Just like @yurzui, said, the issue was “preserveWhitespaces” in Components.

Since the default behaviour of Components is preserve any white spaces.

The two following snippets will result in two different DOM:

<template><tag></tag></template>

<template>
    <tag></tag>
</template>

A

<div *ngFor="...">

Will have no trailing space in the DOM, and this is the source of difference.

To achieve the same behavior, we can set preserveWhiteSpaces to false;

Answered By – Danilo

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *