1

谁能发现这段代码有什么问题,我没有将事件返回给 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 的响应,也没有得到调试器。

4

3 回答 3

1

您对事件发射器的绑定错误。您需要绑定到Output参数,而不是绑定到发出(dataEmit而不是returnData)事件并替换getTest1Data为的函数getToggle

<app-test1 [mytext1]="childmessage" (dataEmit)="getToggle($event)"></app-test1>
于 2018-08-27T12:01:08.907 回答
1

您的输出名称是dataEmit. 因此,从此重构您的组件调用

   <app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>

对此:

   <app-test1 [mytext1]="childmessage" (dataEmit)="getTest1Data($event)"></app-test1>
于 2018-08-27T12:01:31.367 回答
1

问题在这里:

<app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>

(returnData) 应该是 (dataEmit)

dataEmit 是实际事件(事件发射器类型) returnData 只是单击按钮时调用的方法:)

getTest1Data($event) 也应该是 getToggle($event)

希望这可以帮助。

于 2018-08-27T12:01:39.290 回答