Angular 2中* *内的字符串连接

String concatenation within *ngfor Angular 2

本文关键字:字符串 连接 Angular      更新时间:2023-09-26

我想在*ngfor angular 2指令中加入多行字符串。

var contacts = [str1, str2, str3];
<div *ngFor="let c of contacts;let last = last; let str = str + c;">
    <div *ngIf="last">
         {{str}}
    </div>
</div>
我知道上面的代码是无效的。但我想知道上面的东西是可能实现的吗?

预期输出应为

Str1

Str2

Str3

注意:我想在c#中使用angular的ngfor实现下面的代码。

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

也许像join这样简单的东西就足够了:

未经考验的

var contacts = ['str1', 'str2', 'str3'];
<div [innerHtml]="contacts.join('')"></div>

update

*ngFor可用于根据前项计算值。最好的方法是在代码中准备列表,然后将*ngFor绑定到生成的列表。

原来

不能在let中使用任意表达式。只有*ngFor提供的上下文变量可以被赋值。

这样就会产生你想要的结果

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

您可以简单地依次输出两个字符串:

let contacts = [str1, str2, str3];
<div *ngFor="let c of contacts;let last = last;">
    <div *ngIf="last">
         {{str}}{{c}}
    </div>
</div>