Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

callback - In Angular how do I define a "router" member field?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should really read the angular guide at angular.io, but just to get you going as close to your implementation as possible.

The parent component:

<form id="statForm" method="get">
    <app-item-menu [default_selected]="itemId"
                        (valueChangeCallback)="onNavigate($event)"></app-item-menu>
</form>

The child component:

<select id="item" (change)="valueChangeCallback.emit($event)">
    <option *ngFor="let item of items"
        [selected]="item.id === default_selected">{{item.path}}</option>
</select>

And make your valueChangeCallback an output property, instead of an input:

//...
Output()
valueChangeCallback: EventEmitter<any> = new EventEmitter();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...