简体   繁体   English

Angular2:* ngFor,AsyncPipe和index

[英]Angular2: *ngFor, AsyncPipe, and index

In a previous question here , I am trying to show a date only when it has changed between 2 messages. 此处的上一个问题中,我试图仅在两条消息之间发生更改时才显示日期。

The difference is that I am now connected to a realtime database (Firebase), so I subscribe to the data source and pass it through the async pipe before going through index and *ngIf: 不同之处在于我现在已经连接到实时数据库(Firebase),所以我订阅了数据源并通过异步管道传递它,然后通过索引和* ngIf:

<div *ngFor='let message of (chat | async) ; let i = index'>
    <button *ngIf="i == 0 || (message.timestamp | date: 'ddMMMMyyyy') != ((chat | async)[i-1].timestamp | date: 'ddMMMMyyyy')">
        {{ message.timestamp | date:'ddMMM' }}
    </button>
    ...
    <!--More html elements below (omitted)-->
    ...
</div>

This works well when I first load the view, however, if I push a new entry into chat , I get the following error: 这在我第一次加载视图时效果很好,但是,如果我将一个新条目推入chat ,我会收到以下错误:

TypeError: Cannot read property '0' of null

Maybe I am not too sure how the async pipe works, but when I try returning {{ (chat | async).length }} , it works as intended. 也许我不太确定异步管道是如何工作的,但是当我尝试返回{{ (chat | async).length }} ,它按预期工作。 Any suggestions on a workaround/proper practice? 有关变通方法/正确练习的任何建议吗?

如果其他人发现这个,因为它是关键词的第一个结果,我能够像这样使用异步管道得到* ngFor的索引(假设messages是可迭代的Observable):

<div *ngFor="let message of (messages | async); let i = index;">

Still not sure how the AsyncPipe can be manipulated here, but I did mange to find a workaround that involves not using the pipe. 仍然不确定如何在这里操作AsyncPipe,但我确实找到了一个涉及不使用管道的解决方法。 I will await a better answer hopefully before marking this closed. 我希望在关闭之前等待一个更好的答案。

I subscribe to the data source in my class, and manipulate the array with a for loop before displaying it. 我订阅了我的类中的数据源,并在显示之前使用for循环操作数组。

The (template) code in my question has now become: 我的问题中的(模板)代码现在变为:

<div *ngFor='let message of messages; let i = index'>
    <button *ngIf="message.isNewDay">
      {{ message.timestamp | date:'ddMMM' }}
    </button>
    ...
    <!--More html elements below (omitted)-->
    ...
</div>

And in the controller: 在控制器中:

private chatid: string //chat id passed from previous screen
private chat: FirebaseListObservable<any>;
private messages: any = [];

constructor(private firebase: FirebaseService,
            private _datepipe: DatePipe) {
}

ionViewLoaded() {
    this.chat = this.firebase.database.list('/chat-messages/' + this.chatid);
    this.chat.subscribe((data) => {
        this.messages = data;
        for (let i: number = 0; i < this.messages.length; i++) {
            if (i === 0)
                    this.messages[i].isNewDay = true;
            else {
                let date1 = this._datepipe.transform(this.messages[i].timestamp, 'ddMMMMyyyy');
                let date2 = this._datepipe.transform(this.messages[i-1].timestamp, 'ddMMMMyyyy');
                if (date1 !== date2)
                    this.messages[i].isNewDay = true;
                else
                    this.messages[i].isNewDay = false;
            }
        }
    });
}

Note that I am currently using DatePipe in the class code (as well as in the template), so it is necessary to use providers: [DatePipe] along with pipes: [DatePipe] . 请注意,我目前在类代码(以及模板)中使用DatePipe,因此必须使用providers: [DatePipe]以及pipes: [DatePipe]

As mentioned above by @Primal Zed let company of (filteredCompaniesAliases | async); let i = index" 正如上面提到的@Primal Zed let company of (filteredCompaniesAliases | async); let i = index" let company of (filteredCompaniesAliases | async); let i = index" should do the trick, syntax sample with plain html table: let company of (filteredCompaniesAliases | async); let i = index"应该做的技巧,语法示例与普通的html表:

<table>
   <tr *ngFor="let company of (filteredCompaniesAliases | async); let i = index"">
                <td>
                    {{selectedDiscountableCharge.name}}
                </td>
                <td>
                    ${{selectedDiscountableCharge.amount}}
                </td>
                <td>
                    ${{selectedDiscountableCharge.amount - ( (selectedDiscountableChargePercentanges / 100) * selectedDiscountableCharge.amount ) }}
                </td>
    </tr>
</table>

in your component: 在您的组件中:

companyAliasFilterCtrl: FormControl;
filteredCompaniesAliases: Observable<any[]>;

...

this.filteredCompaniesAliases = this.companyAliasFilterCtrl.valueChanges
.pipe(
  startWith(''),
  map(company => company ? this.filterOperatorsAliases(company) : this.companies.slice())
);

If you want to use *ngFor, AsyncPipe, and index together - you should use this construction: 如果你想一起使用* ngFor,AsyncPipe和index - 你应该使用这种结构:

  <ul>
      <li *ngFor="let person of obsPersons | async as persons; index as i">
           {{i + 1}} out of {{persons.length}}: {{person.personId}}  
       </li>
  </ul> 

Tested and works on Angular 7. 测试并使用Angular 7。

I use a function for showing (or not) the date. 我使用一个函数来显示(或不显示)日期。 So to show the date (in this example) only when it changes: 因此,仅在更改时显示日期(在此示例中):

<ion-list no-lines>
<ion-item-sliding *ngFor="let trip of tripsExt$ | async; let i = index">
  <ion-item>
    <ion-row (click)="change(trip)">
      <ion-col col-6>
        {{showOnChange(trip.date)}}
      </ion-col>
      <ion-col col-6>
        {{trip.end_address_name}}
      </ion-col>
    </ion-row>
  </ion-item>
  <ion-item-options side="left">
    <button ion-button color="primary" (click)="delete(trip)">
      Delete
    </button>
  </ion-item-options>
</ion-item-sliding>
</ion-list>

With showOnChange: 使用showOnChange:

  showOnChange(currentDate) {
    if (currentDate != this.previousDate) {
      this.previousDate = currentDate
      return currentDate
    }
    return ''
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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