How to pass object as component input to ngFor

I am trying to iterate over an array of Audio objects (contains 3 lines) and pass the audio in each iteration to the 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>
...

      

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

+8


source to share


2 answers


Input syntax is incorrect inside parent html. Do the following:



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

      

+14


source


In the 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 that and pass the index then you will get the data as an object.

0


source







All Articles