Angular 7通过单击按钮迭代json

时间:2018-12-25 13:53:03

标签: html arrays json angular typescript

正如我在标题中所述,我想通过按钮单击来遍历我的json响应。见下面我的json文件:

{
    "id": 2,
    "name": "Słownictwo",
    "flashcardLists": [
        {
            "id": 17,
            "frontside": "dasfasdv",
            "backside": "csdascd"

        },
        {
            "id": 18,
            "frontside": "dsadsaad",
            "backside": "sdasdadad"
        },
        {
            "id": 19,
            "frontside": "dasdsadd",
            "backside": "sdaddsa"
        }
    ]
}

FlashcardHTML:

<div  class="flip-container" (click)="flip()" [class.flipped]="flipped" >
    <mat-card-header></mat-card-header>
    <mat-card-content *ngFor="let flashcard of flashcardLists" class="flipper">
    <mat-card class="front">
       {{flashcard.frontside}}
    </mat-card>
    <mat-card class="back">
      {{flashcard.backside}}
    </mat-card>
    </mat-card-content>
</div>

我拥有一次只需要一个“正面”和“背面”的组件。 接下来,将其替换为单击的按钮,这将增加计数器,但我不知道该怎么做。我尝试了类似flashcard[0].frontside的方法,但这是KO。也许有人遇到过同样的问题,可以为我提供帮助。

所有答案在此先感谢

2 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您想翻单张卡。

类似的事情应该做:

<mat-card-content *ngFor="let flashcard of flashcardLists" class="flipper">
  <mat-card [class.front]="!flashcards[i].isFlipped"
            [class.back]="flashcards[i].isFlipped"
            (click)="flashcards[i].isFlipped = !flashcards[i].isFlipped "
            >
     {{ flashcards[i].isFlipped ? flashcard.backside : flashcard.frontside }}
  </mat-card>
</mat-card-content>

只需将此卡片状态映射添加到y0our组件:

flashcards: { [key: string]: boolean } = {};

答案 1 :(得分:0)

您在*ngFor中不需要mat-card-content,而是将其绑定到flipCard变量,该变量将在按钮迭代单击时更改。至于正面或背面,请使用另一个变量isFront,在单击按钮时将对其进行更新。像这样的东西:

component.html

<mat-card>
  <mat-card-header></mat-card-header>
  <mat-card-content class="flipper">
    <div class="front" *ngIf="isFront">
      {{flashcard.frontside}}
    </div>
    <div class="back" *ngIf="!isFront">
      {{flashcard.backside}}
    </div>
  </mat-card-content>
  <mat-card-actions>
    <button (click)="iterate()" class="btn-flashcard" mat-button mat-raised-button id="previous">
      Następna
    </button>
    <button mat-button (click)="flip()" [class.flipped]="flipped">LIKE</button>
    <button mat-button>SHARE</button>
  </mat-card-actions>
</mat-card>

component.ts

flashcardList: any[] // use your flashCard class instead of any
flashcard: any; // use your flashCard class instead of any
isFront = true;

ngOnInit() {
  // init first card
  // flashcard = first card
}

iterate() {
  // logic for getting the next card
  // flashcard = next card
  // e.g.
  let index = this.flashcardList.indexOf(this.flashcard);
  this.flashcard = this.flashcardList[index + 1];
}

flip() {
  this.isFront = !this.isFront;
}