For Angular 9, I have a parent component in which I want to pass a function to a child component. I want to pass the "onNavigate" function to the child component ...
import { Router, ActivatedRoute } from '@angular/router';
...
export class StatsComponent implements OnInit {
constructor(
private router: Router,
private route: ActivatedRoute,
private apiService: ApiService
) { }
...
onNavigate(event): void {
const id = event.target.value;
if(parseInt(id) !== this.itemId) {
const url = `/stats/${this.itemId}`;
this.router.navigateByUrl(url);
}
}
The parent component looks like this ...
<form id="statForm" method="get">
<app-item-menu [default_selected]="itemId"
[value_change_callback]="onNavigate"></app-item-menu>
</form>
The child component looks pretty simple ...
<select id="item" (change)="valueChangeCallback($event)">
<option *ngFor="let item of items"
[selected]="item.id === default_selected">{{item.path}}</option>
</select>
But when I change an item in the menu, I get a
ERROR TypeError: this.router is undefined
in the "onNavigate" method. How else do I need to be defining my router?
question from:
https://stackoverflow.com/questions/65864767/in-angular-how-do-i-define-a-router-member-field 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…