简体   繁体   中英

I need to dynamically allocate an object array to an image carousel container in angular using a loop populated within the component class

My issue rests on what I believe to be a misuse of the image carousel html code structure. Here is my Html:

<div id="carousel-trades" class="carousel slide carousel-fade" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div *ngFor="let ytd of yourTrades; let i = index" class="carousel-item {{ (i == 0) ? 'active' : ''}}">
      <img style="width:310px;height:310px" [src]="splitImageString(ytd.tradeUrl)" (click)="pickImageForTrade(yourTradeImage)"
             alt="First slide">
    </div>
  </div>
</div>

Also I there is the possibility that the array "yourTrades" is not being initialized due to being out of scope.

component.ts file:

yourTrades: Trade[];

ngOnInit(): void {
this.resetForm();
this.serviceTrade.getUserId()
  .subscribe(data => {

    this.myId = data;

    let yourTrades = new Array();

    for (let i = 0; i < this.trades.length; i++) {
      if (this.myId.userId == this.trades[i].userId) {
        yourTrades.push(this.trades[i]);
      }
    }
    console.log(yourTrades);
  })
}

When I call console.log I get the expected array of objects but when my carousel renders it returns empty. It must be the fact that there may be a wrong connection from when "yourTrades" is populated to when it is used by the html?

Change your caraousel html to:-

<div id="carousel-trades" class="carousel slide carousel-fade" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div *ngFor="let ytd of yourTrades; let i = index" class="carousel-item" [ngClass]="{'active': i===0}">
      <img style="width:310px;height:310px" [src]="splitImageString(ytd.tradeUrl)" (click)="pickImageForTrade(yourTradeImage)"
             alt="First slide">
    </div>
  </div>
</div>

You aren't assigning the yourTrades variable inside the subscription to the member variable. Try the following

yourTrades: Trade[] = [];     // <-- assign empty array

this.serviceTrade.getUserId()
  .subscribe(data => {
    this.myId = data;
    for (let i = 0; i < this.trades.length; i++) {
      if (this.myId.userId == this.trades[i].userId) {
        this.yourTrades.push(this.trades[i]);       // <-- directly push to the member variable
      }
    }
    console.log(this.yourTrades);
  });
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM