Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ngFor to create different element types

I am iterating through an array of strings (called words), and want to create span elements for each word, and br elements for end of line characters (\n) using Angular/Typescript. I've got the ngFor directive working:

<div id = documentContents *ngIf="showDocument">
    <span *ngFor="let word of words" >
        {{word}}
    </span>
</div>

It currently creates spans from everything, even the br elements in the array. Note: while parsing the document, I create br elements out of the end of line characters. Not married to this solution, just seemed like a good idea. Logically I want to do something like:

if(word != "<br/>") {
    <span> {{word}} </span>
}
else {
    create a <br/> element
}

Where all the spans and br elements get appended to the containing div and the original source format is maintained (As much as possible)

But am unsure how to implement the ngIf portion. I've experimented with putting the ngFor directive on the containing div element (docContents) but then it generates div elements vice spans (to be expected). I've written something similar using javascript and was just a simple matter of document.append(span or br element). It's probably a simple thing but it escapes me. Appreciate any help.

like image 327
GeoffWillis Avatar asked Dec 29 '25 09:12

GeoffWillis


1 Answers

Place your *ngFor on an <ng-container>, it won't add an extra element to the DOM at runtime.

And put an inner *ngIf with a template reference to an <ng-template> to handle the else part:

<div id = documentContents *ngIf="showDocument">
    <ng-container *ngFor="let word of words" >
        <span *ngIf="word !== '\n'; else br">{{ word }}</span>
        <ng-template #br><br /></ng-template>
    </ng-container>
</div>

Here is an article on <ng-container> if you want more information.

like image 103
jo_va Avatar answered Dec 31 '25 23:12

jo_va