任何人都可以找出这段代码中的错误吗,我没有将事件返回给appcomponent
test1.component.html
<input type="text" [(ngModel)]="mytext1" >
<button
id="clicked"
name="Click Me"
class="button"
(click)="returnData();">
Click Me!
</button>
test1.component.ts
import {
Component,
OnInit,
Input,
Output,
EventEmitter
} from '@angular/core';
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
styleUrls: ['./test1.component.css']
})
export class Test1Component implements OnInit {
constructor() {}
@Input() mytext1: string;
@Output() dataEmit: EventEmitter < string > = new EventEmitter < string > ();;
ngOnInit() {}
changeText1($event) {
this.mytext1 = $event;
}
returnData() {
console.log("button clicked");
this.dataEmit.emit(this.mytext1);
}
}
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>
{{testText2}}
</div>
app.component.ts
import {
Component,
Input,
OnInit
} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'AngularDemo';
public testText2: string = "from parent";
childmessage: string = "I am passed from Parent to child component";
getToggle($event) {
this.testText2 = $event;
}
ngOnInit() {
}
}
我没有收到关于app.component.ts的响应,也没有得到调试器。
答案 0 :(得分:0)
您对事件发射器的绑定错误。您需要绑定到Output
参数,而不是绑定到发出(dataEmit
而不是returnData
)事件的函数,并将getTest1Data
替换为getToggle
<app-test1 [mytext1]="childmessage" (dataEmit)="getToggle($event)"></app-test1>
答案 1 :(得分:0)
您的输出名称为dataEmit
。因此,请从
<app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>
对此:
<app-test1 [mytext1]="childmessage" (dataEmit)="getTest1Data($event)"></app-test1>
答案 2 :(得分:0)
问题在这里:
<app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>
(returnData)应该是(dataEmit)
dataEmit是实际事件(事件发射器类型)returnData只是单击按钮时调用的方法:)
getTest1Data($ event)也应该是getToggle($ event)
希望这会有所帮助。