首页 文章

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

提问于
浏览
3

我在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 回答

  • 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() {
      }
    }
    

    希望它有所帮助,蒂埃里

相关问题