I want to make divs in loop and show the div I choose by press of specific button. In theory I see this like the following... using *ngFor i construct divs and buttons for them lets say
<div>div1</div><button (click)="showDiv(divID)">showDIV</button>
To hide div I must use ngIf
<div *ngIf="Here I must place something wih divID">>div1</div><button (click)="showDiv(divID)">showDIV</button>
And in ts file I must set value of something with divID to TRUE when I press it's button.
So how can I do that something, I guess it must be array or something else. Please give me solution example of what must be written in template and ts file
part of ts file for dynamical array building.
data.length=6
i=1
data.forEach(element => {
Here I want to add variable to array
this.i++;
});
You could define an array in the controller like
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
});
}
}
}
And use it to display the buttons dynamically in the template
<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>
Working example: Stackblitz
Docs: *ngFor
and *ngIf
directives, expression interpolation, <ng-container>
tag.
If you're new to Angular, I'd also recommend you to go through the official tutorial. It introduces all these basics.