两个组件之间的角度通讯

时间:2018-10-31 12:31:34

标签: javascript angular typescript components

我正在使用angular构建一个基于Web的简单应用程序。

有两个组成部分。一个组件是另一组件的子组件。子组件中有一个按钮。当我单击子组件中的按钮时,我想调用父组件的函数。我该怎么做。

我认为这与角度@Output有关。但是我管理不了。

这是我的代码的组织方式。

父组件-component.ts文件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-teacher-home',
  templateUrl: './teacher-home.component.html',
  styleUrls: ['./teacher-home.component.scss']
})
export class TeacherHomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  formView: boolean = false;

  toggleForm(){
    this.formView = !this.formView;
  }
}

父组件-component.html文件

<div>
    <child-compnent></child-compnent>
</div>

子组件-component.html文件

<div>
    <button>Toggle Form view</button>
</div>

单击子组件中的按钮时,我想调用父组件的功能toggleForm()

4 个答案:

答案 0 :(得分:4)

阅读此文章:Understanding @Output and EventEmitter in Angular

子组件:

@Component({
  selector: 'app-child',
  template: `<button (click)="sendToParent('hi')" >sendToParent</button> `
})
export class AppChildComponent {
  @Output() childToParent = new EventEmitter;

  sendToParent(name){
    this.childToParent.emit(name);
  }
}

父组件:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  toggle(){
    console.log('toggle')
  }

}

父html:

<app-child (childToParent)="toggle($event)"></app-child>

工作DEMO

答案 1 :(得分:4)

您有两种方法可以做到这一点:

  1. 是在子组件内部创建一个事件,然后为其提供回调,如下所示:

    @Output('eventName') buttonPressed = new EventEmitter();

并在需要触发事件时致电buttonPressed.emit()

在父端看起来像这样:

<div>
    <child-compnent (eventName)="toggleForm()"></child-compnent>
</div>
  1. 另一种方法是创建一个共享服务,其中将包含两个组件的共享功能和数据

答案 2 :(得分:3)

您需要在子组件内部使用@Output装饰器,并在您的孩子内部单击当前按钮时发出一个事件。

例如:-

子component.html

<div>
    <button (click)="childButtonClicked()">Toggle Form view</button>
</div>

子component.ts

export class ChildComponent {
  @Output triggerToggle: EventEmitter<any> = new EventEmitter<any>();

  ...
   childButtonClicked() {
     this.triggerToggle.emit(true);
   }
  ...
}

父组件

<div>
    <child-compnent (triggerToggle)="toggleForm()"></child-compnent>
</div>

答案 3 :(得分:2)

您可以使用EventEmitter的角度来监听子组件中的事件。

parent.component.ts

toggleForm($event) {} 

parent.component.html

<div>
    <child-compnent  (trigger)="toggleForm($event)" ></child-compnent>
</div>

child.component.ts

@Output() trigger : EventEmitter<any> = new EventEmitter<any>();

buttonClick(){
  this.trigger.emit('click');
}