在ngOnInit()上发出事件

时间:2017-09-22 21:21:38

标签: angular

尝试在初始化期间从子组件向父组件发出事件。 onchange事件工作正常,但似乎没有任何东西在init上启动。

事件来自选择菜单,我们以默认选择值2开始关闭选择菜单,我们需要父母知道此值:

子组件HTML:

<!-- Show Season Dropdown -->
<div style="float:right">
    <select id="seasonDropDown" aria-label="Select a Season">
                  <option *ngFor="let item of seasons" [value]="item.id" [selected]="item.id === seasonId">Season {{item.id}}</option>
              </select>
</div>

子组件:

 @Output() notify: EventEmitter<number> = new EventEmitter<number>();

  ngOnInit() {
    this.notify.emit(2);
    this.getSeasons();
  }

  public changeSeason(seasonId: number) {
    console.log('change season ' + seasonId)
    this.seasonId = seasonId;
    this.notify.emit(this.seasonId);
  }

我们在父页面上有这个组件:

<app-seasons-dropdown (notify)="onNotify($event)"></app-seasons-dropdown>

我们在父组件中有这个监听器:

  onNotify(event:Event):void {
    console.log('notify');
    const seasonId = (event.target as HTMLSelectElement).value;
    this.getLeaderboardBySeason(Number(seasonId));
  }

0 个答案:

没有答案