簡體   English   中英

兩個組件之間的角度通訊

[英]Angular communication between two components

我正在使用角度版本6構建一個簡單的基於Web的應用程序。

在我的應用程序中,有一個包含子組件的組件。 該組件中有一個函數(在父組件中,而不是子組件。),我想使用子組件中的按鈕來調用該函數。

此圖像說明了我的組件的格式。

在此處輸入圖片說明

我認為它與angular @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()父組件的功能toggleForm()

閱讀本文: 了解Angular中的@Output和EventEmitter

子組件:

@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>

工作演示

您有兩種方法可以做到這一點:

  1. 是在子組件內部創建一個事件,然后為其提供回調,如下所示:

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

並希望觸發事件時調用buttonPressed.emit()

在父端,它將如下所示:

<div>
    <child-compnent (eventName)="toggleForm()"></child-compnent>
</div>
  1. 另一種方法是創建一個共享服務,其中將包含兩個組件的共享功能和數據

您需要在子組件內部使用@Output裝飾器,並在孩子內部單擊當前按鈕時發出事件。

例如:-

子component.html

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

子組件

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

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

父組件

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

您可以使用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');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM