nacho_dh
nacho_dh

Reputation: 1937

How to pass object as component input in ngFor

I'm trying to iterate over an array of Audio objects (contains 3 strings) and passing the audio in each iteration to a child component.

app.component.ts

ngOnInit(){
    this.audios = new Array<SoundBoardAudio>();
    this.audios.push(new SoundBoardAudio('Western','La canción del Sheriff.','western.mp3'));
    this.audios.push(new SoundBoardAudio('Olvidelo Amigo','Busquese otro tonto amigo.','olvidelo_amigo.mp3'));
  }

app.component.html

<div class="container">
   <app-soundcard *ngFor="let audio of audios" soundBoardAudio=audio></app-soundcard>
</div>

soundboard.component.ts

export class SoundcardComponent implements OnInit {

  audio:any;

  constructor() {}

  @Input() soundBoardAudio;

  ngOnInit() {
    console.log(this.soundBoardAudio);
    let audioSrc = 'assets/audio/'+this.soundBoardAudio.filename;
    this.audio = new Audio(audioSrc);
  }
...

soundboard.component.html

<div class="card" >
  <div class="card-block">
    <h2 class="card-title">{{soundBoardAudio.name}}</h2>
    <p>{{soundBoardAudio.desc}}
  </div>
</div>
...

But when I try to read the audio from the child component, I get an undefined value. If I only pass a string instead of an object, it works ok.

Upvotes: 17

Views: 29350

Answers (2)

Mario Petrovic
Mario Petrovic

Reputation: 8332

Your input syntax is not correct inside parent html. Do like this:

<div class="container">
  <app-soundcard *ngFor="let audio of audios" [soundBoardAudio]="audio"/>
</div>

Upvotes: 24

In your parent component

<div *ngFor="let pollData of PollList ; let i index" >            
    <app-pollinfo [masterArray]="i"></app-pollinfo>
</div>

in your child component

@Input() masterArray : any;

use this and pass index then you will get data as object.

Upvotes: 1

Related Questions