Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

arrays - How to display a h2 once using *ngFor and *ngIf

I have an array of words consisting of 2, 3, 4, 5 and so on letter words. im using an ng-For to iterate through the array and ng-if to display the words according to the amount of letters but i cant seem to get a title in to separate them

expected outcome

2 letter words to am as .......

3 letter words the bee sin .......

and so on,

this is what i have so far

<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>

i know i should also be using an index to iterate through the sized words, ill get to that after :)

question from:https://stackoverflow.com/questions/65865963/how-to-display-a-h2-once-using-ngfor-and-ngif

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make use of a Pipe to transform the array of words into an object whose key is the length of the word and whose values are the words themselves.

@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;
    }

}

Now you can easily use this on your template with the following syntax:

<div *ngFor="let word of words | groupByWordsPipe | keyvalue">
    <h2>{{word.key}}</h2> letter words : {{word.value}}
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...