I have an object say:
persons = [
{
name: 'A',
occupation: 'a',
},
{
name: 'B',
occupation: 'b',
},
{
name: 'C',
occupation: 'c',
},
];
And I have a dynamic dialog to be opened that contains this data:
*ngFor=
<h2>Name</h2>
<p> {{persons.name}} </p>
<h2>Occupation</h2>
<p> {{persons. occupation}} </p>
And I have a table with buttons in it. How can I make every button open next different popup dialog with data provided? I am struggling with *ngFor but can't seem to make it happen.
I have two components: overview that contains table, and details that contains data and dialog they are siblings (not parent child related).
This table does NOT contain this exact data, but some other.
Here is visual representation of what I want to achieve:
What approach should I use?
CodePudding user response:
Here is a example in Stackblitz
In the example you have a component (the start dialog we say). At this the options (Employees or whatever) are hosted.
@Component({
selector: 'hello',
template: `<div *ngFor="let data of testData">
<div>{{data.name}}</div>
<button (click)="onClick(data)">CLICK</button>
</div>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
@Output() onItemClick: EventEmitter<{ name: string; data: string }> =
new EventEmitter();
testData = [
{ name: 'Test 1', data: 'something' },
{ name: 'Test 2', data: 'something 2' },
{ name: 'Test 3', data: 'something 3' },
];
onClick(data: { name: string; data: string }) {
// Better use a interface
this.onItemClick.emit(data);
}
}
And in App Component you show the "clicked" Employees:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' VERSION.major;
showDialogsSet: Set<{ name: string; data: string }> = new Set();
onItemClicked(data: { name: string; data: string }) {
// Again: use a interface
if (this.showDialogsSet.has(data)) this.showDialogsSet.delete(data);
else this.showDialogsSet.add(data);
console.log(data);
}
}
HTML Part of this (The div
with the *ngFor can be a other component as well):
<div>
<hello (onItemClick)="onItemClicked($event)"></hello>
<hr>
<div *ngFor="let data of showDialogsSet">{{data.name}} - {{data.data}}</div>
</div>
You can click the button - Component will show. Click again - Component hide. Try and test it!