I'm trying to pass an input text data from child component to Parent.
Passed data then added to the array of objects.
Using *ngFor i'm displaying all the array objects.
Issue is, newly added value is empty only empty li is getting added
Console Issue:
App Component.
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>
Add Hero Component
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); } }
Looks like you are passing there just a string
, instead of Herotype
. Try it like this:
newAddedHero(name) {
this.heroes.push(new Herotype({name}));
}
Or just:
newAddedHero(name) {
this.heroes.push({name});
}
{name}
is ES6 shorthand for {name: name}
. You can name your method parameter as you wish, so I renamed it to name
to use this shorthand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.