[英]Angular communication between two components
我正在使用角度版本6構建一個簡單的基於Web的應用程序。
在我的應用程序中,有一個包含子組件的組件。 該組件中有一個函數(在父組件中,而不是子組件。),我想使用子組件中的按鈕來調用該函數。
此圖像說明了我的組件的格式。
我認為它與angular @Output
有關。 但是我管理不了。
這就是我的代碼的組織方式。
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;
}
}
<div>
<child-compnent></child-compnent>
</div>
<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>
工作演示
您有兩種方法可以做到這一點:
是在子組件內部創建一個事件,然后為其提供回調,如下所示:
@Output('eventName') buttonPressed = new EventEmitter();
並希望觸發事件時調用buttonPressed.emit()
在父端,它將如下所示:
<div>
<child-compnent (eventName)="toggleForm()"></child-compnent>
</div>
您需要在子組件內部使用@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.