簡體   English   中英

Angular 5 EventEmitter效果不佳

[英]Angular 5 EventEmitter Not working well

我試圖在子組件上調用父組件功能,並像這樣實現。

項目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');
   }
}

項目form.component.html

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

項目view.component.ts

export class ProjectViewComponent implements OnInit {

  projects: Project[];
  projectform: Project;

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

項目view.component.html

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

這里當我點擊子組件的New按鈕時,我只能在控制台上看到"submit"而不是"create Project on parent component"

這意味着不發出事件或父母未收到事件。 基本上,我錯過了一些東西。
請為我分享任何類型的打擊。

你錯過了一件事@artgb, createProject(event:string){}你試試這個。

實際上我嘗試了你的代碼,它在Angular 5.0.0上工作正常。 當我點擊New('submit'和'create Project ...')時,我收到兩條控制台消息。 我認為你的問題可能與EventEmitter沒有直接關系。 您提供的代碼片段直接編譯並運行以下amendements(如果您要測試它):

  1. 添加缺少的導入

  2. 添加ngOnInit

  3. 刪除引用“項目”模型的所有屬性

所以我發現你當前的代碼沒有任何問題。 您的問題可能在其他地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM