获取listview中的当前元素

问题描述 投票:0回答:2

我正在开发一个简单的信使。我想实现消息看/看不见的功能。我如何获得标记元素的位置,这些元素是否在listview内的wrap布局内?

enter image description here

这是我用来呈现消息的代码。

<ListView (loaded)="testLoad($event)"
   #chatBox
   separatorColor="transparent"
   class="chat-box"
   [items]="messages"
  (loaded)="scrollChatToBottom()"
  row="0">
  <ng-template let-item="item">
  <StackLayout 
    class="bubble-container">
    <Label
        [text]="item.createdAt | timeAgo"
        class="message-date-{{bubbleClass(item)}} SourceSansPro- 
   LightItalic"></Label>
    <WrapLayout 
      [class]="bubbleClass(item)" orientation="horizontal">
      <!--<Image 
      [src]="item.sender.pictureUrl"
      [class]="bubbleClass(item) + '-picture'">e></Imag-->
      <TextView
        editable="false"
        class="message-content SourceSansPro-Regular"
        [text]="item.messageBody"></TextView> 

    </WrapLayout >

    </StackLayout>
   </ng-template>
 </ListView>
chat nativescript nativescript-angular
2个回答
1
投票

ListView的整个想法是根据需要重用View(模板),只有数据可能不同,但在滚动时,View的相同实例将被重用于不同的索引。

因此,通常您应该通过数据控制View。如果您计划将读取消息显示为粗体/浅色或不同颜色,则可以通过CSS完成,因此只需根据数据项中的读/未读标志绑定正确的类。

如果您仍想访问实际的View元素,可以使用RadListView。我认为目前没有一种简单的方法可以访问ListView中的View实例。


1
投票

我不知道ListView,但我总是可以使用指令来获取ElementRef。如果你有ElementRef,你可以得到el.nativeElement.offsetTop。

所以,它唯一能做的就是:

@Directive({
  selector: '[pos]'
})
export class PosDirective  {
  @Input('pos') index:number;
  el:ElementRef
  constructor(el:ElementRef){ 
    this.el=el;
   }
}

我们的指令需要“索引”。我在<p>中使用了一个简单的例子

<p [pos]="i" *ngFor="let item of data;let i=index">{{item}}</p>
<button (click)="showPos(0)">click</button>

我们使用ViewChildren“获取p”(实际上是指令)

  @ViewChildren(PosDirective)positions:QueryList<PosDirective>;

  showPos(index:number)
  {
    const elem=(this.positions.toArray()[index]) as PosDirective;
    console.log(elem.el.nativeElement.offsetTop)
  }

stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.