I have 3 sections coming from loop. Also I have 3 buttons. Here I need to show only first section('one') by default and first button should be active.When I click second button second section should show only and second button should be active..so on. Here is the code below https://stackblitz.com/edit/angular-hccv44?file=src%2Fapp%2Fapp.component.ts
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div *ngFor="let data of testJson">{{data.name}}</div>
<div style="margin-top:10px"><button>click1</button></div>
<div><button>click2</button></div>
<div><button>click3</button></div>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
testJson = [
{
id: 1,
name: 'one'
},
{
id: 2,
name: 'two'
},
{
id: 3,
name: 'three'
}
];
name = 'Angular';
ngOnInit() {}
}
it's easy. You only need a variable for know the section activated.
In "app.component.ts" you will have:
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() {}
}
And in your 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>
You can try it:
https://stackblitz.com/edit/angular-pcmjaf?file=src%2Fapp%2Fapp.component.html
You can leverage a component library like angular material to have some fancy, toggleable buttons. The you can run the loop over the buttons as well to create as many as you like.
<ng-container *ngFor="let data of testJson">
<div *ngIf="data.id == number">
{{data.name}}
</div>
</ng-container>
<mat-button-toggle-group [(ngModel)]="number" aria-label="Font Style">
<mat-button-toggle *ngFor="let data of testJson" [value]="data.id">{{data.name}}</mat-button-toggle>
</mat-button-toggle-group>
export class AppComponent implements OnInit {
number = 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.