Show one div on click of the other without using *ngIf

When I click on 1st <div> it should hide, when I click on 2nd <div> the second <div> should hide but 1st should appear. Similarly when I click on any <div> it should hide but other hidden <div> should appear. What I achieved is, onclick on <div> it is hidding but onclick of another <div> the hidden <div> is not appearing back. Please suggest what to do.

NOTE: I have to iterate over and hide the same and I cannot use *ngIf and *ngFor on same

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

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

  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 answer

  • answered 2018-05-16 06:22 Fussel

    No to pretty, but something like this in your component

    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;

    And in your 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">

    Here is a working stackblitz btw.