Угловой скрыть div с определенным индексом - PullRequest
0 голосов
/ 04 мая 2018

Новый для машинописи, я должен скрыть div, на котором нажал пользователь.

Ниже мой код:

<div class="tiles" *ngFor="let episode of episodes; let i = index" (click)="showDetails(i)" style="width:100px;height:100px;border:2px solid black">
  {{episode.title}}
</div>

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  showDiv:boolean = false;

episodes = [
    { title: 'Winter Is Coming', director: 'Tim Van Patten' },
    { title: 'The Kingsroad', director: 'Tim Van Patten' },
    { title: 'Lord Snow', director: 'Brian Kirk' },
    { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' },
    { title: 'The Wolf and the Lion', director: 'Brian Kirk' },
    { title: 'A Golden Crown', director: 'Daniel Minahan' },
    { title: 'You Win or You Die', director: 'Daniel Minahan' },
    { title: 'The Pointy End', director: 'Daniel Minahan' }
  ];

  showDetails(i):void{
    this.showDiv = !this.showDiv;
  }
}

Всего 8 делений будут заполнены вышеуказанным кодом. Таким образом, как только 1-й элемент будет нажат, он должен спрятаться, и другие элементы div должны занять его место, аналогично, при нажатии на 2-й элемент div он должен скрыться (1-й должен появиться видимым), а другие элементы div должны занять его место.

Ответы [ 5 ]

0 голосов
/ 04 мая 2018

Добавить атрибут showDiv для объекта каждого эпизода.

Пример:

episodes = [{showDiv: true, title: 'xxxxxx', ....}]
0 голосов
/ 04 мая 2018

Вот один из способов сделать это (не нужно никаких переменных в компоненте. Вся логика в шаблоне:

<div class="tiles" *ngFor="let episode of episodes; let i = index" (click)="showDetails(i)" style="width:100px;height:100px;border:2px solid black">
   <span #itm [hidden]="itm[i]" (click)="itm[i] = true ">{{episode.title}}</span>
</div>

p.s. Вы можете заменить [hidden] на *ngIf, чтобы производительность в большинстве случаев увеличилась

0 голосов
/ 04 мая 2018

Попробуйте это

<div *ngFor="let episode of episodes; let i = index">
  <div class="tiles" *ngIf='i !== hide' (click)="hide = i" style="width:100px;height:100px;border:2px solid black">
    {{episode.title}} {{i}}
  </div>
</div>

Рабочий пример

0 голосов
/ 04 мая 2018

Я не буду использовать ngFor, в этом случае мы практически реализуем карусель, и вам больше не нужно использовать ngFor или ngIf, и вы продолжаете цикл объектов (эпизодов)

app.component.html

 <div class="tiles" (click)="showNext()" style="width:100px;height:100px;border:2px solid black">
  {{currentEpisode.title}}
 </div>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public currentEpisode: any = {};
  currentIndex: number = -1;

  episodes = [
    { title: 'Winter Is Coming', director: 'Tim Van Patten' },
    { title: 'The Kingsroad', director: 'Tim Van Patten' },
    { title: 'Lord Snow', director: 'Brian Kirk' },
    { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' },
    { title: 'The Wolf and the Lion', director: 'Brian Kirk' },
    { title: 'A Golden Crown', director: 'Daniel Minahan' },
    { title: 'You Win or You Die', director: 'Daniel Minahan' },
    { title: 'The Pointy End', director: 'Daniel Minahan' }
  ];

  showNext(): void {
    this.currentIndex = (this.currentIndex + 1) == this.episodes.length ? 0 : this.currentIndex + 1;
    this.currentEpisode = this.episodes[this.currentIndex];

  }

  ngOnInit() {
    this.showNext()
  }
}

Рабочий пример на стеке

0 голосов
/ 04 мая 2018

Идея состоит в том, чтобы иметь переменную indexHidden, когда indexHidden == i, вы скрыли "div". Но вы не можете сделать это за тот же «div».

Итак, мы используем ng-контейнер https://angular.io/guide/structural-directives#ng-container-to-the-rescue, чтобы сделать * ngFor

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

//in your component.ts
indexHidden:number=-1 //At first equal=-1, so all episodes are showed
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...