typescript Angular 5 EventEmitter 工作不正常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47200666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:01:30  来源:igfitidea点击:

Angular 5 EventEmitter Not working well

angulartypescriptcomponentseventemitter

提问by artgb

I am trying to call Parent Component function on Child Component, and implemented like this.

我试图在子组件上调用父组件函数,并像这样实现。

project-form.component.ts

项目-form.component.ts

@Component({
  selector: 'app-project-form',
  templateUrl: './project-form.component.html',
  styleUrls: ['./project-form.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ProjectFormComponent implements OnInit {

  @Input() project: Project;
  @Output() createProject = new EventEmitter<string>();

  newProject() { 
    console.log("submit");
    this.createProject.emit('submit');
   }
}

project-form.component.html

项目-form.component.html

<button (click)="newProject()" class = "btn-success" >New</button>

project-view.component.ts

项目-view.component.ts

export class ProjectViewComponent implements OnInit {

  projects: Project[];
  projectform: Project;

  createProject(event){
    console.log("create Project on parent component");
  }
}

project-view.component.html

项目视图.component.html

<app-project-form [project]="projectform" (createProject)="createProject($event)"></app-project-form>

Here when I click on Newbutton of child component, I can only see "submit"on console but not "create Project on parent component".

在这里,当我单击New子组件的按钮时,我只能"submit"在控制台上看到而不能在"create Project on parent component".

It means event is not emitted or parent not received event. Basically, I missed something.
Please share any kind of hit for me.

这意味着未发出事件或未收到父级事件。基本上,我错过了一些东西。
请为我分享任何类型的打击。

采纳答案by Jacobys527

You missed one thing @artgb, createProject(event:string){}You try this.

你错过了一件事@artgb,createProject(event:string){}你试试这个。

回答by Sameh Awad

Actually I tried your code, and it is working fine on Angular 5.0.0. I get two console messages when I click on New ('submit' and ' create Project ...'). I think your problem might not be directly related to the EventEmitter. The code snippets you have provided compile and run directly with the following amendements (if you want to test it):

实际上我试过你的代码,它在 Angular 5.0.0 上运行良好。单击“新建”(“提交”和“创建项目...”)时,我收到两条控制台消息。我认为您的问题可能与 EventEmitter 没有直接关系。您提供的代码片段通过以下修改直接编译和运行(如果您想对其进行测试):

  1. Add missing imports

  2. Add ngOnInit

  3. Remove any properties referencing 'Project' model
  1. 添加缺失的导入

  2. 添加 ngOnInit

  3. 删除任何引用“项目”模型的属性

So I can not find anything wrong with your current code. Your problem might be elsewhere.

所以我找不到你当前的代码有什么问题。您的问题可能在其他地方。