ListView 而不是 *ngFor

ListView istead of *ngFor

我在 NativeScript 中使用 ScrollView 作为聊天概览。

到目前为止,我一直将此代码用于滚动视图:

<ScrollView #scrollLayout style="height: 80%;margin-top: -200px">

   <StackLayout class="chat-body">
        <StackLayout *ngFor="let message of messages"  orientation="vertical">

                <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-message-me" [text]="message.msg"></Label>
                <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-timestamp" [text]="message.time"></Label>
            
                <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-message-you" [text]="message.msg"></Label>
                <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-timestamp" [text]="message.time"></Label>
        
        </StackLayout> 
    </StackLayout>

</ScrollView>

它起作用了,但是当我向消息数组添加一个新元素时,视图会将完整的数组加载到已经显示的数组之上。

消息数组:

聊天视图:

所以我的解决方案是使用 ListView,如下所示:

<ScrollView #scrollLayout style="height: 80%;margin-top: -200px">
    <GridLayout class="chat-body">
        <ListView [items]="messages" orientation="vertical">
            <ng-template let-item="message">
                
                <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-message-me" [text]="message.msg"></Label>
                <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-timestamp" [text]="message.time"></Label>
            
                <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-message-you" [text]="message.msg"></Label>
                <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-timestamp" [text]="message.time"></Label>

                
            </ng-template>
        </ListView>
   </GridLayout>
</ScrollView>

但我得到这个错误:

System.err: An uncaught Exception occurred on "main" thread.
System.err: Calling js method getView failed
System.err: Error: No suitable views found in list template! Nesting level: 0
System.err:

ListView 自动滚动,因此您不需要 ScrollView 父项。

您看到的错误是因为 ListView 内部需要一个 component/layout(您有 4 个标签)。

要修复错误,您可以将标签包裹在 ContentView 或这样的布局中:

<ListView [items]="messages" orientation="vertical">
  <ng-template let-message="item">
    <ContentView>
      <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-message-me" [text]="message.msg"></Label>
      <Label *ngIf="message.sender == me" horizontalAlignment="right" class="chat-timestamp" [text]="message.time"></Label>      
      <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-message-you" [text]="message.msg"></Label>
      <Label *ngIf="message.sender != me" horizontalAlignment="left" class="chat-timestamp" [text]="message.time"></Label>
    </ContentView>
  </ng-template>
</ListView>

但是,在 ListView 中使用 ngIfs 会对性能产生一些影响。如果可能,请改用多个项目模板。 blog post 对这两种方法进行了深入比较。