Angular 2:子组件直接emit到父组件的脚本文件
Angular 2: emit from child component directly to the parent component's script file
我有一个嵌套组件,我希望在不通过模板的情况下将一些数据直接发送到父打字稿文件。 我不会用<child (childEvent)="parentFunc()"></child>
这可能吗?如果是这样,如何?
这是目前的情况。
parent.component.html(元素必须是这个)
<child #child> </child>
parent.component.ts
@ViewChild('child') public child;
public doSomething() {
this.child.work();
}
public doThisWhenChildEmits(someData) {
//?????How do I call this function from child without going through the DOM
alert(It worked)
}
child.component.ts
@Output() private childEvent: EventEmitter<any> = new EventEmitter()
...
public work() {
// does some work that changes the child's template
}
public clickToSendBack(){
// click event that sends back to parent.component directly????
this.childEvent.emit(someData);
}
如果您不想使用 @Output
,您可以使用 Subject
:
您的 parent 会订阅更改。在您的 parent 中,在组件中声明一个 Subject 并在构造函数中订阅更改:
public static changesMade: Subject<any> = new Subject();
//inside constructor the following
ParentComponent.changesMade.subscribe(res => {
//call your method here, with the res (someData) you receive from child
this.doThisWhenChildEmits(res);
});
在你的 child:
public clickToSendBack(){
// send the data to parent
ParentComponent.changesMade.next(someData)
}
如果有帮助请告诉我! :)
我有一个嵌套组件,我希望在不通过模板的情况下将一些数据直接发送到父打字稿文件。 我不会用<child (childEvent)="parentFunc()"></child>
这可能吗?如果是这样,如何?
这是目前的情况。
parent.component.html(元素必须是这个)
<child #child> </child>
parent.component.ts
@ViewChild('child') public child;
public doSomething() {
this.child.work();
}
public doThisWhenChildEmits(someData) {
//?????How do I call this function from child without going through the DOM
alert(It worked)
}
child.component.ts
@Output() private childEvent: EventEmitter<any> = new EventEmitter()
...
public work() {
// does some work that changes the child's template
}
public clickToSendBack(){
// click event that sends back to parent.component directly????
this.childEvent.emit(someData);
}
如果您不想使用 @Output
,您可以使用 Subject
:
您的 parent 会订阅更改。在您的 parent 中,在组件中声明一个 Subject 并在构造函数中订阅更改:
public static changesMade: Subject<any> = new Subject();
//inside constructor the following
ParentComponent.changesMade.subscribe(res => {
//call your method here, with the res (someData) you receive from child
this.doThisWhenChildEmits(res);
});
在你的 child:
public clickToSendBack(){
// send the data to parent
ParentComponent.changesMade.next(someData)
}
如果有帮助请告诉我! :)