[英]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.