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
448 views
in Technique[技术] by (71.8m points)

angular - 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?

question from:https://stackoverflow.com/questions/65864328/how-do-i-pass-a-callback-function-to-a-child-component

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

1 Reply

0 votes
by (71.8m points)

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

(change)="valueChangeCallback($event)"

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

...