Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object as component input in ngFor

Tags:

angular

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.

like image 427
nacho_dh Avatar asked Apr 30 '17 23:04

nacho_dh


2 Answers

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>
like image 150
Mario Petrovic Avatar answered Oct 13 '22 18:10

Mario Petrovic


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.

like image 35
Harsha Vardhan Reddy N Avatar answered Oct 13 '22 18:10

Harsha Vardhan Reddy N