从子节点发送数据并添加它Parent Array

时间:2017-11-01 18:42:18

标签: angular

我试图将输入文本数据从子组件传递给Parent。

传递数据,然后添加到对象数组中。

使用* ngFor i显示所有数组对象。

问题是,新添加的值是空的,只有空的li被添加

控制台问题:

enter image description here

应用程序组件。



const HEROES: Herotype[] = [{
    name: 'Mr. Nice'
  },
  {
    name: 'Narco'
  },
  {
    name: 'Bombasto'
  }
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Tours of Hero';
  heroes = HEROES;
  myFav = this.heroes[0];

  selectedHero: string;

  onclick(hero: string) {
    this.selectedHero = hero;
    console.log(this.selectedHero)
  }

  newAddedHero($event) {
    this.heroes.push($event)
    // console.log (this.heroes.push($event));
  }
}

<div class="container">
  <h1>{{title}}</h1>
  <h2>My Favorite hero is <b>{{myFav.name}}</b></h2>

  <ul>
    <li *ngFor="let hero of heroes" (click)="onclick(hero)">
      {{hero.name}}
    </li>
  </ul>
  <app-addhero (newHero)="newAddedHero($event)"></app-addhero>
</div>
&#13;
&#13;
&#13;

添加英雄组件

&#13;
&#13;
export class AddheroComponent implements OnInit {

  addedHero: string;

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

  addHero(value) {
    this.addedHero = value;
    this.newHero.emit(this.addedHero)
    console.log(this.addedHero);
  }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

看起来你只是string,而不是Herotype。试试这样:

newAddedHero(name) {
  this.heroes.push(new Herotype({name}));
}

或者只是:

newAddedHero(name) {
  this.heroes.push({name});
}

{name}{name: name}的ES6简写。您可以根据需要为方法参数命名,因此我将其重命名为name以使用此简写。