Javascript 如何在点击按钮时隐藏和显示来自循环的部分-角度8

Javascript 如何在点击按钮时隐藏和显示来自循环的部分-角度8,javascript,angular,Javascript,Angular,我有3节来自loop。我还有3个按钮。在这里,默认情况下我只需要显示第一部分(“一”),第一个按钮应该是活动的。当我单击第二个按钮时,第二部分应该只显示,第二个按钮应该是活动的。依此类推。下面是代码 app.component.html 这很容易。您只需要一个变量就可以知道激活的部分 在“app.component.ts”中,您将拥有: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'm

我有3节来自loop。我还有3个按钮。在这里,默认情况下我只需要显示第一部分(“一”),第一个按钮应该是活动的。当我单击第二个按钮时,第二部分应该只显示,第二个按钮应该是活动的。依此类推。下面是代码

app.component.html
这很容易。您只需要一个变量就可以知道激活的部分

在“app.component.ts”中,您将拥有:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  button_selected = 1;
  testJson = [
    {
      id: 1,
      name: 'one'
    },
    {
      id: 2,
      name: 'two'
    },
    {
      id: 3,
      name: 'three'
    }
  ];
  name = 'Angular';
  ngOnInit() {}
}
在app.component.html中

<p>
  Start editing to see some magic happen :)
</p>
<div *ngFor="let data of testJson">
  <div *ngIf="data.id==button_selected">
    {{data.name}}
  </div>

</div>

<div style="margin-top:10px">
  <button *ngFor="let data of testJson" 
  style="display:block" 
  (click)="button_selected=data.id" 
  [disabled]="button_selected==data.id"
  >
    click {{data.id}}
  </button>
</div>

开始编辑以查看发生的奇迹:)

{{data.name} 单击{{data.id}
你可以试试:


您可以利用像Angle material这样的组件库来拥有一些奇特的、可切换的按钮。您也可以在按钮上运行循环来创建任意数量的按钮


{{data.name}
{{data.name}
导出类AppComponent实现OnInit{
数字=1;

类似这样的内容:?感谢您的回答,我可以将其更改为不同的/活动的颜色吗?是的,您可以使用[ngClass]=“condition?”class1':“class2'”来决定特定的css类,也可以使用[ngStyle]=“condition?”styles1':“styles2'”来直接更改样式
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  button_selected = 1;
  testJson = [
    {
      id: 1,
      name: 'one'
    },
    {
      id: 2,
      name: 'two'
    },
    {
      id: 3,
      name: 'three'
    }
  ];
  name = 'Angular';
  ngOnInit() {}
}
<p>
  Start editing to see some magic happen :)
</p>
<div *ngFor="let data of testJson">
  <div *ngIf="data.id==button_selected">
    {{data.name}}
  </div>

</div>

<div style="margin-top:10px">
  <button *ngFor="let data of testJson" 
  style="display:block" 
  (click)="button_selected=data.id" 
  [disabled]="button_selected==data.id"
  >
    click {{data.id}}
  </button>
</div>