@Output没有完全与父母沟通

时间:2018-05-03 10:11:37

标签: html angular

我尝试在两个组件之间进行通信,但单击按钮时我的@Output()似乎无法正常工作。访问该功能不是问题,因为我可以从控制台获得响应。

子-comp.component.html:

     <div class="container" style="text-align: center" style="padding-top: 10px">
  <label>The Child text is: {{goodbye}} </label>
   <p></p>
   <p>The parent input is : {{state}} </p>
   <button class="primary" (click)='sendToParent()'>Send to Parent</button>
 </div>

父 - comp.component.html:

     <div class="container" style="text-align: center" style="padding-top: 
 10px">
     <label>The Parent text is: {{hello}}</label>
         <p></p>
    <p>The Child input is : {{goodbye}} </p>
 </div>
     <hr>
 <app-child-comp [state]="hello" (event)="setDataFromChild()"></app-child- 
 comp>

 child-comp.component.html:

   <div class="container" style="text-align: center" style="padding-top: 
     10px">
  <label>The Child text is: {{goodbye}} </label>
  <p></p>
  <p>The parent input is : {{state}} </p>
  <button class="primary" (click)='sendToParent()'>Send to Parent</button>
</div>

子-comp.component.ts:

    import { Component, OnInit, Input, Output, EventEmitter} from 
'@angular/core';

@Component({
        selector: 'app-child-comp',
        templateUrl: './child-comp.component.html',
        styleUrls: ['./child-comp.component.css'],
  })
export class ChildCompComponent implements OnInit {
@Input() public state: string;
@Output() event: EventEmitter<string> = new EventEmitter();

 public goodbye = 'goodbye';
  constructor() { }

  ngOnInit() {
  }
  sendToParent()  {
    this.event.emit(this.goodbye);
  }
}

父 - comp.component.ts:

    import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-parent-comp',
   templateUrl: './parent-comp.component.html',
   styleUrls: ['./parent-comp.component.css']
})
 export class ParentCompComponent implements OnInit {


  public hello = 'hello';
  public goodbye: string;
  constructor() { }

   ngOnInit() {
  }
   public setDataFromChild(data) {
    this.goodbye = data;
     console.log('event emitted');
   }
 }

1 个答案:

答案 0 :(得分:3)

你不接受来自EventEmitter的数据:

改变这个: (event)="setDataFromChild()"

要:

(event)="setDataFromChild($event)"