问题
I am quite new to angular and am trying to create a little app that utilises dynamic routing. I have a "members" page that lists all current members whereby if you click on one specific member you load another page used for displaying the user detail. Currently I am just trying to display "You have clicked on xxxs profile" but I am having trouble working out how to get the clicked user name displayed..
Member component:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
@Component({
selector: 'app-members',
template: `
<li *ngFor='let members of members' (click)='onSelect(members)'>
<span class='badge'> {{members.name}} : {{members.id}} </span>
</li>
` ,
styleUrls: ['./members.component.css']
})
export class MembersComponent implements OnInit {
members = [
{'id': 1, 'name': 'Person 1'},
{'id': 2, 'name': 'Person 2'},
{'id': 3, 'name': 'Person 3'}
];
constructor(private router: Router) { }
ngOnInit() {
}
onSelect(members) {
this.router.navigate(['/member', members.id]);
}
}
I am at a loss as to how I should go about displaying the clicked profile name inside of the member component, anyone care to suggest a solution to me?
member component:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, ParamMap, Router } from '@angular/router';
import { MembersComponent } from '../members.component';
@Component({
selector: 'app-member',
template: `
You have clicked on {{ ****to be displayed**** }} profile!
`,
styleUrls: ['./member.component.css']
})
export class MemberComponent implements OnInit {
constructor(private router: ActivatedRoute ) { }
ngOnInit() {
}
}
回答1:
Along with the above solution, you can pass the name in query params, if you don't mind the name in the URL..
Under Members component:
onSelect(members) {
this.router.navigate(['/member', members.id], {queryParams: {name: members.id}});
}
Under Member component:
...
template: `You have clicked on {{memberName}} profile!`,
...
public memberName: string = "";
public subs$;
constructor(private _route: ActivatedRoute) ...
ngOnInit() {
this.subs$ = this._route
.queryParams
.subscribe((params) => {
this.memberName = params["name"];
})
}
// this is to kill the subscription
ngOnDestroy() {
if (this.subs$) {
this.subs$.unsubscribe();
}
}
回答2:
There are two ways you can pass data into components, using EventEmmiters EventReceiver
@Input()
or with a service.
In this case since you are using two independent (not parent/child) you should use service to communicate between two components
来源:https://stackoverflow.com/questions/50583627/how-to-display-clicked-user-profile-data-in-a-different-component