2017-08-01 39 views
1

我有以下對象:如何直接在角度4的模板綁定中增加變量?

this.people = [{ 
     name: 'Douglas Pace', 
     title: 'Parcelivery Nailed The Efficiency', 
     content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' + 
      'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy', 
     image: '../../assets/img/profile_pics/profile_pic.jpg', 
     rate: '4.5', 
     classActive: 'testimonials__selected-visible', 
     active: true 
     }, 
     { 
     name: 'Naseebullah Ahmadi', 
     title: 'Parcelivery Nailed The Efficiency', 
     content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' + 
      'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy', 
     image: '../../assets/img/profile_pics/profile_pic.jpg', 
     rate: '4.5', 
     classActive: '', 
     active: false 
     }, 
     { 
     name: 'Haseebullah Ahmadi', 
     title: 'Parcelivery Nailed The Efficiency', 
     content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' + 
      'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy', 
     image: '../../assets/img/profile_pics/profile_pic.jpg', 
     rate: '4.5', 
     classActive: '', 
     active: false 
     } 
    ]; 

,我喜歡這樣的循環這樣的HTML:

<ng-template ngFor let-person="$implicit" let-variable [ngForOf]="people"> 
      {{variable + 30}} 
    <ng-template/> 

我的問題是,是否有有一個局部變量,並通過30增加它的一種方式對於模板綁定中的ngfor中的每個元素?而不是有方法來增加?

,我有遞增從方法變量的問題是,我得到以下錯誤:

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

+0

你需要增加哪個數組的字段 –

+0

目前我只是想創建一個隨機變量來增加。我不想在對象中添加一個字段並增加它。這只是爲了說明我的問題。但是,我使用一個API,我得到的對象,所以我不能修改。 @sachilaranawaka – James

回答

3
<ng-template ngFor let-person="$implicit" let-variable [ngForOf]="people" let-i="index"> 
    <p *ngIf="i == 0">{{variable + 30}}</p> 
    <p *ngIf="i > 0">{{variable + (30*i)}}</p> 
<ng-template/> 

通過這個你從0開始總長度的指標。

+0

因此對於3個項目的集合,上述返回'0,30,60'。我可以接受30,60,90嗎? – James

+0

順便說一句,當我打印時,變量返回對象內的當前元素和索引,這是錯誤的。 – James

+0

「變量」的類型是什麼?嘗試單獨打印索引'i'並檢查獲得正確的值。你可以使用'* ngIf'跳過0 – Hareesh