循环构建 div 并在按下按钮时显示它们 angular

building divs in loop and show them on button press angular

我想循环 divs 并通过按下特定按钮显示我选择的 div。 从理论上讲,我看到的是这样的...... 使用 *ngFor 我为它们构造 divs 和按钮 让我们说

<div>div1</div><button (click)="showDiv(divID)">showDIV</button>

要隐藏 div 我必须使用 ngIf

 <div *ngIf="Here I must place something wih divID">>div1</div><button (click)="showDiv(divID)">showDIV</button>

并且在 ts 文件中,当我按下它的按钮时,我必须将带有 divID 的东西的值设置为 TRUE。

那么我该怎么做呢,我猜它一定是数组或其他东西。 请给我解决方案示例,必须在模板和 ts 文件中写入什么

动态阵列构建的 ts 文件的一部分。

data.length=6
i=1
        data.forEach(element => {
Here I want to add variable to array
          this.i++;
        });

你可以像这样在控制器中定义一个数组

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

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

  ngOnInit() {
    for (let i=1; i<=5; i++) {
      this.buttons.push({
        id: i, show: false
      });
    }
  }
}

并使用它在模板中动态显示按钮

<div *ngFor="let button of buttons">
  <button (mouseup)="button.show = !button.show">
    {{ button?.show ? ('Hide ' + button?.id) : ('Show ' + button?.id) }}
  </button>
  <ng-container *ngIf="button?.show">
    Content for button {{ button?.id }}
  </ng-container>
</div>

工作示例:Stackblitz

文档:*ngFor and *ngIf directives, expression interpolation, <ng-container> tag.

如果您是Angular的新手,我也建议您通过官方tutorial。它介绍了所有这些基础知识。

您可以通过以下方式实现您的要求。

请参考下例 示例代码:

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  divisions = [
    {
      content: 'Div 1 content .......',
      visibility: false
    },
    {
      content: 'Div 2 content .......',
      visibility: false
    },
    {
      content: 'Div 3 content .......',
      visibility: false
    },
    {
      content: 'Div 4 content .......',
      visibility: false
    },
  ];

  toggleDiv(index: number) {
    this.divisions[index].visibility = !this.divisions[index].visibility;
  }
}

app.component.html

<div class="container">
  <ng-container *ngFor="let div of divisions;let i=index">
    <div class="div-btn">
      <button type="button" (click)="toggleDiv(i)" class="btn btn-primary">{{div.visibility===false? 'Show': 'Hide' }}
       Div {{i+1}}</button>
    </div>
    <div *ngIf="div.visibility" class="div-content">{{div.content}}</div>
  </ng-container>
</div>

app.component.css

.div-content {
  height: 100px;
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px;
}

.div-btn{
  padding: 10px;
  margin: 10px;
}