Angular 4 - 从子组件调用父方法无效

Angular 4 - Calling a parent method from a child component not working

我的所有事件发射器都正常工作,只有一个除外。

child.ts:

@Component({
    ... 
    outputs: ['fileUploaded']
    })

export class childComponent implements OnInit {
  ...
  fileUploaded = new EventEmitter<boolean>();
  ...
  randomMethod(){
     ...
     this.fileUploaded.emit(true);
  }

}

randomMethod() 是从父组件调用的,我将在 parent.ts。它没有在 child.html.

中调用

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..

parent.ts

export class parentComponent {
   ...
   theChild = new childComponent;
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
     this.theChild = new childComponent;
  }
}

我的应用程序从不记录 "in onSubmit()" 那么为什么不调用此方法?我还尝试不在最后一行创建新的子对象,但这并没有什么不同。

这样试试:

@Output()
  fileUploaded = new EventEmitter<boolean>();

并删除:

outputs: ['fileUploaded']

检查文档 here! :D

您不应使用 new 运算符创建子组件。

您应该使用 @ViewChild() 来引用子组件。

也许我不清楚你为什么选择这种方法或者你需要它做什么,但据我所知,你应该使用从子到父的 EventEmitter。 这意味着触发 .emit() 的事件应该放在 child.html 中。 尝试这样做,它应该可以工作:

child.html

<div (click-or-whatever-fires-what-you-want)="randomMethod()"></div>

child.ts:

@Component({
    ... 
    })

export class childComponent implements OnInit {
  ...
  @Output() fileUploaded = new EventEmitter<boolean>();
  ...
  randomMethod(){
     ...
     this.fileUploaded.emit(true);
  }

}

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..

parent.ts

export class parentComponent {
   ...
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }
}

希望对您有所帮助。

你选择的子组件是错误的,你应该这样使用ViewChild

parent.html:

<child #theChild (fileUploaded)="onSubmit($event)"></child>

parent.ts:

export class parentComponent {
   ...
   @ViewChild('theChild') theChild;
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
  }
}

您可以使用@Output 发射器从子组件调用父组件的方法,该发射器在子组件上的任何事件上触发。我在评论部分使用这种方法使用子组件的方法更新父组件中的计数。

Parent.ts

/** Update the count from child component */
UpdateCount(id) {
this.getTotalCommentCountByGroupId(id);
}

Parent.HTML

 <srv-group-feed [LiveFeedInput]="groupPostRes" 
 (CommentCount)="UpdateCount($event)"></srv-group-feed>

Child.ts

 this.CommentCount.emit(data you need to pass);

在全局范围内,您可以在子组件中声明 @Output 事件,即 child.ts

@Output() CommentCount = new EventEmitter<string>();