如何从子组件中调用父组件中的事件?

时间:2016-02-01 10:06:07

标签: typescript angular

我已经在我有表格和附件的地方实施了标签。 tab1中的按钮。我在父组件中有一个事件,它使当前标签无效并且下一个标签处于活动状态。如何从子组件中调用父组件中的事件?

  gotosecondtab(){
this.firsttabactive=false;
this.secondtabactive=true;
}

这是父组件中的事件...我想从子组件

运行此事件
onSubmit(): void {  
console.log('you submitted value: ', this.myForm.value); 
//How to call the parent event here
}

当我执行onSubmit()事件时,我想运行gotosecondtab()事件...请有人帮助我

1 个答案:

答案 0 :(得分:6)

您可以在子组件中创建自定义事件

@Component({
  selector: 'child',
  (...)
})
export class ChildComponent {
  @Output() myevent: EventEmitter;

  constructor() {
    this.myevent = new EventEmitter();
  }

  onSubmit(): void {  
    console.log('you submitted value: ', this.myForm.value); 
    this.myevent.emit();
  }
}

并从父组件注册:

@Component({
  template: `
    <child (myevent)="gotosecondtab()"></child>
  `,
   directives: [ ChildComponent ]
  (...)
})
export class ParentComponent {
  (...)

  gotosecondtab() {
  }
}

希望它有所帮助, 亨利

相关问题