[英]How to display a h2 once using *ngFor and *ngIf
我有一个由 2、3、4、5 等字母单词组成的单词数组。 我使用 ng-For 遍历数组和 ng-if 来根据字母的数量显示单词,但我似乎无法获得标题来分隔它们
预期结果
2 个字母的单词作为.......
蜜蜂罪的三个字母词......
等等,
这就是我到目前为止所拥有的
<div *ngIf="data">
<h2 class="title">{{data.letters}}</h2>
<ul class="wordList" *ngFor="let item of data.word">
<li *ngIf="item.length ==2">{{item}}</li>
<li *ngIf="item.length ==3">{{item}}</li>
<li *ngIf="item.length ==4">{{item}}</li>
<li *ngIf="item.length ==5">{{item}}</li>
<li *ngIf="item.length ==6">{{item}}</li>
<li *ngIf="item.length ==7">{{item}}</li>
<li *ngIf="item.length ==8">{{item}}</li>
<li *ngIf="item.length ==9">{{item}}</li>
<li *ngIf="item.length ==10">{{item}}</li>
<li *ngIf="item.length ==11">{{item}}</li>
<li *ngIf="item.length ==12">{{item}}</li>
<li *ngIf="item.length ==13">{{item}}</li>
<li *ngIf="item.length ==14">{{item}}</li>
</ul>
</div>
我知道我还应该使用索引来遍历大小写的单词,之后我会说:)
使用Pipe
将单词数组转换为 object,其键是单词的长度,其值是单词本身。
@Pipe({ name: 'groupByWordsPipe' })
export class GroupByWordsPipe implements PipeTransform {
transform(input: []) {
let map = {};
input.forEach((e: string) => {
if (map[e.length]) {
map[e.length] = map[e.length] + ' ' + e;
} else {
map[e.length] = e;
}
});
return map;
}
}
现在,您可以使用以下语法轻松地在模板上使用它:
<div *ngFor="let word of words | groupByWordsPipe | keyvalue">
<h2>{{word.key}}</h2> letter words : {{word.value}}
</div>
我认为您必须在 class 中处理按长度分组的部分,并构建一个合适的 object 结构来包含您要显示的数据。 另请注意,由于您有一个按字长排列的组列表和每个组的单词列表,您实际上需要两个嵌套的 * ngFor声明。
在您的 class 中:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
private words = ['the', 'to', 'am', 'as', 'bee', 'sin', 'other'];
groupedByLength: { length: string, words: string[] }[] = [];
ngOnInit() {
this.groupByLength();
}
private groupByLength() {
let grouped = {};
for(let word of this.words) {
const length = word.length;
if(!grouped[length]) {
grouped[length] = [word];
} else {
grouped[length].push(word);
}
}
Object.keys(grouped).forEach(key => {
this.groupedByLength.push({ length: key, words: grouped[key] });
});
}
}
在您的模板中:
<div *ngFor="let data of groupedByLength">
<h2>{{ data.length }} letter words:</h2>
<ul>
<li *ngFor="let word of data.words">{{ word }}</li>
</ul>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.