Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...