在不使用* ngIf的情况下单击另一个显示一个div

时间:2018-05-16 06:13:20

标签: angular typescript

当我点击第一<div>时,它应该隐藏,当我点击第二个<div>时,第二个<div>应隐藏但第一个应该出现。同样,当我点击任何<div>时,它应隐藏,但应显示其他隐藏的<div>。我取得的成就是,点击<div>它正在隐藏但是另一个<div>点击隐藏的<div>没有出现。请建议做什么。

注意:我必须迭代并隐藏相同的内容,我不能在同一个上使用* ngIf和* ngFor

    <hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<div *ngFor="let episode of episodes; let i = index" (click)="episode.showDiv = false" style="width:100px;height:100px;border:2px solid black">
  tile{{i}}  
</div>


import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  hide = null;
  episodes = [
    { title: 'Winter Is Coming', director: 'Tim Van Patten', 'showDiv': true },
    { title: 'The Kingsroad', director: 'Tim Van Patten', 'showDiv': true },
    { title: 'Lord Snow', director: 'Brian Kirk', 'showDiv': true },
    { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk', 'showDiv': true },
    { title: 'The Wolf and the Lion', director: 'Brian Kirk', 'showDiv': true },
    { title: 'A Golden Crown', director: 'Daniel Minahan', 'showDiv': true },
    { title: 'You Win or You Die', director: 'Daniel Minahan', 'showDiv': true },
    { title: 'The Pointy End', director: 'Daniel Minahan', 'showDiv': true }
  ];


}

1 个答案:

答案 0 :(得分:1)

不是很漂亮,但在你的组件中有类似的东西

onClick(event: any) {
     for(let i = 0; i < this.episodes.length; i++) {
         if(this.episodes[i] == event) {
              this.episodes[i].showDiv = false;
         } else {
              this.episodes[i].showDiv = true;
         }
     }
}

在你的HTML中

<ng-container *ngFor="let episode of episodes; let i = index">
    <div class="tiles" *ngIf="episode.showDiv" (click)="onClick(episode)" style="width:100px;height:100px;border:2px solid black">
        tile{{i}}
    </div>
</ng-container>

Here是一个有效的stackblitz btw。