satish
satish

Reputation: 943

How do I pass a callback function to a child component?

I'm writing an Angular 9 app and I have this shared component to produce a select menu ...

export class SharedMenuComponent implements OnInit {

  items: Item[] = [];
  // Represents what is selected by default
  @Input('default_selected') default_selected: number;
  @Input('value_change_callback') valueChangeCallback: any;

  constructor(
    private route: ActivatedRoute,
    private apiService: ApiService
  ) {}

  ngOnInit(): void {
    this.items = this.route.snapshot.data.items;
  }

}

The HTML looks like

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

I'm noticing the "onChange" callback isn't invoked when someone selects a different item from the menu. In the parent component, I call the child component like this

<form id="statForm" method="get">
    <app-item-menu [default_selected]="itemId"
                        [value_change_callback]="onNavigate"></app-item-menu>
</form>

I define this function in the parent component

  onNavigate(event): void {
    console.log("called on change ...");
  }

The console.log never gets printed and the function doesn't seem like it's called at all. What else do I need to do to get my callback invoked?

Upvotes: 2

Views: 1768

Answers (1)

Raz Ronen
Raz Ronen

Reputation: 2628

Like @MikeOne mentioned, you need to actually invoke the callback:

(change)="valueChangeCallback($event)"

Upvotes: 2

Related Questions