Reputation: 529
I want to send a variable to another component.
HTML-doc in component A where I want to send user.id to component B
<li class="list-group-item list-group-item-action" *ngFor="let user of users">
<a routerLink="/profile" routerLinkActive="active" (click)="testFunc(user.id)">
{{user.name}}
</a>
</li>
Component A where I want to send the id to component B (This is where I'm stuck)
testFunc (id: JSON): string {
//Send to component B
}
I don't know if this is enough information but I can provide with more if needed.
Upvotes: 0
Views: 57
Reputation: 1513
If I understand your code when you click on the link you go to /profile page. So if the content B is the profile component you can send your user.id throw the router parameter like:
<a [routerLink]="['/profile', user.id]">
Of course configure the right route before. You can check these documentations:
In app.module.ts
const appRoutes: Routes = [
{path: 'addProfile', component: AddProfileComponent },
{path: 'listProfiles', component: ListProfilesComponent},
{path: 'profile/:id', component: ProfileComponent}
]
And
In ProfileComponent
export class ProfileComponent implements OnInit {
private selectedId: number;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.paramMap
.switchMap(params => this.selectedId = +params.get('id');
// second option
this.route.params.subscribe(params => this.selectedId = +params['id'])
}
}
OR
If when you click on the link you just want to send a value to a component which is in your page, you can use @Input decorator. Like this :
<componentA>
<li class="list-group-item list-group-item-action"
*ngFor="let user of users">
<a routerLink="/profile" routerLinkActive="active"
(click)="testFunc(user.id)">{{user.name}}</a>
</li>
<componentB [inputName]="userId"></componentB>
</componentA>
In the ts files:
import { Component, Input } from '@angular/core';
@Component({
selector: 'componentA',
templateUrl: 'url'
})
export class ComponentA {
public userId: string = ""
constructor() {}
public function testFunc(id: string): void {
this.userId = id
}
}
....
import { Component, Input } from '@angular/core';
@Component({
selector: 'componentB',
templateUrl: 'url'
})
export class ComponentB implements OnInit {
@Input() inputName: string;
constructor() {}
function ngOnInit(): void {
console.log(inputName)
}
}
Be careful, don't try to show your input variable into constructor that doesn't work
Upvotes: 1