在ngOnInit中更新变量后,角度4 ngIf未切换

时间:2018-01-11 02:19:14

标签: javascript angular angular-ng-if

我正在使用Angular v4并在我的模板中有* ngIf:

<div class="product-list row" *ngIf="products.length > 0">
  <div *ngFor="let product of products" class="product-container">
    ...
  </div>
</div>

在我的组件文件中我有:

public products = [];

....

public ngOnInit(): void {
  this.productsService.all().toPromise().then( (data: Product[]) => {
    this.products = data;
  });
}

然而,在设置products后,不会切换ngIf。当我添加一个按钮并手动设置变量时,将切换ngIf!

我尝试将if语句更改为products?.length > 0,但它也不起作用。

1 个答案:

答案 0 :(得分:0)

从这篇文章中找到我的答案: Triggering change detection manually in Angular

根据Angular的文件https://angular.io/api/core/ChangeDetectorRef

$('.wrapper').append('\ <div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\ <div class="game-cards">\ <div class="chart-container">\ <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\ </div>\ <div class="right-info">\ <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\ <h5 id="time-channel">'+ gameDate +' @ ' + gameTime + '<br>' + ' On ' + network +'</h5>\ <div class="total-points-live">\ <h5>Total Points Bet</h5>\ <h5 class="total-points" id="point-total">'+ totalPoints +'</h5>\ <p>'+ awayTeam +'</p>\ <input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\ <p>'+ homeTeam +'</p>\ <input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\ <p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\ </div>\ </div>\ </div>\ ');

因此,通过应用detectChanges,Angular将手动检查并更新节点。