我有一个ts文件app.component.ts,其中有一个布尔变量“ flag”,我创建了一个名为dialog的组件,我需要从dialog.ts的app.component.ts中设置变量。
我已经看到EventEmmitter可以做到这一点,但是以某种方式对我不起作用。
@Output() selectionDialogEvent=new EventEmitter<boolean>();
this.selectionDialogEvent.emit("true");
在我正在尝试的父母中
getSelectionDialogEvents($event){
console.log("Event received"+$event);
this.chat=flag;
}
答案 0 :(得分:1)
有很多方法可以做到这一点,一种方法是使用提供程序共享数据,请参见here,但是在这种特殊情况下,我想这段代码可以为您提供帮助:
app-parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
app-child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hello World!"
@Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
答案 1 :(得分:0)
您必须收听调用子组件的事件。然后,当事件触发时,请在父组件中调用您的函数。
<app-child (selectionDialogEvent)=getSelectionDialogEvents($event)></app-child>
其中 $ events 将保存由您的发射器selectionDialogEvent传递的数据
答案 2 :(得分:0)
父组件 Html
<hello (ParentComponet)="ParentComponent($event)"></hello>
父组件 ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// First Make function
ParentComponent(data) {
console.console(data); // this data of child will show in parent console window
}
}
子组件 Html
<button type="button" (click)="sendData()">Send Data P to Child</button>
子组件 ts
import { Component , OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'hello',
templateUrl:'hello-component.html'
})
export class HelloComponent implements OnInit {
// Pass OutPut and EventEmitter
@Output() ParentComponet:EventEmitter<any> = new EventEmitter()
ngOnInit():void{
}
// Make A function
sendData(){
this.ParentComponet.emit('Send Data Child to Parent')
//emit is a function and you can pass the value
}
}