chenk
chenk

Reputation: 482

String concatenation within *ngfor Angular 2

I would like to join strings in multiline within *ngfor angular 2 directive.

var contacts = [str1, str2, str3];

<div *ngFor="let c of contacts;let last = last; let str = str + c;">
    <div *ngIf="last">
         {{str}}
    </div>
</div>

I know the above code is not valid. But I want to know something like above is possible to achieve?

Expected Output should be

Str1

Str2

Str3

Note: I want to achieve something like below code in C# using a angular ngfor.

   var str = "";

   foreach(var item in items)
   {
     str = str + item.toString();
   }
   console.log(str);

Upvotes: 4

Views: 10111

Answers (3)

Poul Kruijt
Poul Kruijt

Reputation: 71961

Perhaps something as simple as join would suffice:

untested

var contacts = ['str1', 'str2', 'str3'];

<div [innerHtml]="contacts.join('')"></div>

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658017

update

*ngFor can be used to calculate values depending on previous items. The best way would be to prepare the list in code and then just bind *ngFor to that resulting list.

original

You can't use arbitrary expressions with let. Only context variables provided by *ngFor can be assigned.

This way it should produce the results you want

<div *ngFor="let c of contacts;let last = last">
    <div *ngIf="last">
         {{str}}{{c}}
    </div>
</div>

Upvotes: 2

Supamiu
Supamiu

Reputation: 8731

You can simply output the two strings one after another:

let contacts = [str1, str2, str3];

<div *ngFor="let c of contacts;let last = last;">
    <div *ngIf="last">
         {{str}}{{c}}
    </div>
</div>

Upvotes: 1

Related Questions