I'm currently working on an angular project and I need some help with this problem...
I displayed the data from an array and next I need to save the value from the element I click so I can display it on another component and play with this value with an API link
This is the code from the component where I display data
<div >
<ul >
<li mat-dialog-close
routerLink='/admin'
*ngFor="let t of data"
>
{{t}}
</li>
</ul>
</div>
How can I save the value of 't' on click so I can use it on another component
The data array is created like this
this.service.getPosts()
.subscribe(response => {
this.posts = response;
this.num = this.posts.body.paginationinfo.numberofelementsTotal;
for(this.i=0;this.i<this.num;this.i )
{
this.test.push(this.posts.body.listOfUnapprovedChangeRequests[this.i].requestuuid);
}
});
console.log(this.test);
}
openDialog(){
this.dialogRef.open(MenupopupComponent,{data:this.test})
}
CodePudding user response:
You can pass it as a query param.
<ul >
<li
mat-dialog-close
routerLink="/admin"
[queryParams]="{ requestId: t }"
*ngFor="let t of data"
>
{{ t }}
</li>
</ul>
Then read that requestId
query parameter with the help of the ActivatedRoute
:
export class AdminComponent {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
const requestId = this.route.snapshot.paramMap.get('requestId');
console.log('requestId', requestId);
}
}
CodePudding user response:
There are many ways using which you can share data between components,
- Parent to Child: via Input
- Child to Parent: via Output() and EventEmitter
- Child to Parent: via ViewChild
- Unrelated Components: via a Service
Here, in your case, you can use 4th one (via a Service).
Create one variable in service and save the value which you want in the service variable on click event of li element. In another component, you can access that value.
reference: https://www.dotnettricks.com/learn/angular/sharing-data-between-angular-components-methods