Eventemitter不会将数据从子组件发送到父组件

时间:2019-03-11 21:15:20

标签: angular

app-component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  test="";
  type:string;
  title=[{Sname:'Test',Scontent:'Test',Stype:'test'}];
  public OnServerAdded(Data:{name:string,content:string}) {
     this.type="Main";
     this.title.push({Sname:Data.name,Scontent:Data.content,Stype: this.type});
  }
}

app-component.html

<app-cockpit (Servercreated)="OnServerAdded($event)"></app-cockpit>
<hr>
<p *ngFor="let a of title">
{{a.Sname}}
</p>

cockpit.component.ts

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


@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
 @Output() Servercreated=new EventEmitter<{Servername:string,ServerContent:string}>();
 @Output() Bluecreated=new EventEmitter<{Servername:string,ServerContent:string}>();
 newServerName= "";
 newServerContent = "";
 Add="";
  constructor() { }
  public ServerAdded()
  {
  this.Servercreated.emit({Servername:this.newServerName,ServerContent:this.newServerContent});
  this.Add="add"
  }
  public BlueAdded()
  {
  this.Servercreated.emit({Servername:this.newServerName,ServerContent:this.newServerContent});
  }
  ngOnInit() {
  }

}

cockpit.component.html

<div class="container">
    <div class="row">
  <div class="col-md-12">

      <p>Add new Servers or BluePrint</p>

        <label>Server Name</label>
        <input type="text" class="form-control" [(ngModel)]="newServerName">
        <label>Server Content</label>
        <input type="text" class="form-control" [(ngModel)]="newServerContent">      
        <br>
        <button class="btn btn-primary" (click)="ServerAdded()" type="button">Add Server</button> &nbsp;
        <button class="btn btn-danger" (click)="BluePrintAdded()" type="button">Add Server</button> &nbsp;
        <p></p>
    </div>
  </div>
</div>

我正在尝试使用事件发射器将事件从子组件发射到父组件,并使用ngFor显示它。发射器不起作用。 我试图将事件从Cockpit组件发送到App组件,并使用ngFor显示少量数据。

2 个答案:

答案 0 :(得分:0)

我认为您正在观看Angular 7-MaximilianSchwarzmüller在Udemy上创建的完整指南。这是一门非常好的课程。只需将您的代码与讲师编写的代码进行比较即可。

您粘贴在此处的代码甚至无法编译!因此,我们无法为您提供详细的解决方案。下面列出了一些常规解决方案:

在app-component.ts中,某些部分丢失了。还要确保在所有方法和属性名称中都遵循驼峰式或帕斯卡式大小写。

答案 1 :(得分:0)

为什么您看不到ngFor的原因是在座舱中发射了具有以下属性的对象:

  public ServerAdded() {
    this.Servercreated.emit({ 
      Servername: this.newServerName, 
      ServerContent: this.newServerContent 
    });
    this.Add = "add"
  }

服务器名和服务器内容。但是在接收方,您尝试像这样推送它:

this.title.push({Sname:Data.name,Scontent:Data.content,Stype: this.type});

尝试将此行更改为此:

this.title.push({ Sname: Data.Servername, Scontent: Data.ServerContent, Stype: this.type });

检查此stackblitz的可用版本。