Ionic 2如何使ion-list从底部向上增长?

4

这是我的代码要点:

<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of array">{{item.name}}</ion-item>
  </ion-list>
</ion-content>
<ion-footer>
  <ion-searchbar (ionInput)="search()"></ion-searchbar>
</ion-footer>

这个想法是在屏幕底部有一个搜索栏,上面是一个列表,该列表根据搜索栏的输入内容而变化。然而,如果项目很少,则此代码将使列表从顶部向下填充,并在其与搜索栏之间留下很多空白空间。我希望该列表紧贴搜索栏(基本上与ion-content底部对齐),同时仍保持在ion-content内可滚动。有哪些方法可以实现这一点呢?


数据来自JSON响应吗? - Sam5487
2个回答

7

可用的 Plunker

要将 ion-list 元素推到底部,您需要执行以下操作:

  • 将视图封装设置为无
  • 使用 display: flexflex-direction: column 样式对 ion-list 容器进行样式设置
  • 使用 margin-top: auto 样式设置 ion-list 元素

不需要更改您的 HTML 模板,此处有一个很好的答案可以说明如何将内容推到容器底部。

组件装饰器

@Component({
  selector: 'page-home',
  templateUrl: 'pages/home/home.html',
  styles: [`
    .scroll-content {
      display: flex;
      flex-direction: column;
    }
    .scroll-content ion-list {
      margin-top: auto;
      margin-bottom: 0;
    }
  `],
  encapsulation: ViewEncapsulation.None
})

3

@adriancarriger的回答很好,但可以进行小改进。由于您正在将新元素推到列表底部,因此最好始终将内容滚动到底部,以使新项目始终可见。这可以通过添加几行代码轻松实现:

// First add ViewChild and Content imports
import { ViewChild, Component, ViewEncapsulation } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'pages/home/home.html',
  styles: [`
    .scroll-content {
      display: flex;
      flex-direction: column;
    }
    .scroll-content ion-list {
      margin-top: auto;
      margin-bottom: 0;
    }
  `],
  encapsulation: ViewEncapsulation.None
})
export class HomePage {
  @ViewChild(Content) content: Content; // <-- get a reference of the content

  count = 4; // for demo
  appName = 'Ionic App';
  array = [
    { name: 'item-1' },
    { name: 'item-2' },
    { name: 'item-3' }
  ];

  constructor(private navController: NavController) {

  }
  search() {
    console.log('searching...');
  }
  add(number) {
    let itemNumber = this.count;
    this.array.push({ name: 'item-' + itemNumber });
    this.scrollToBottom(); // <- when the new item is pushed, scroll to the bottom to show it
    this.count += number;
  }

  scrollToBottom(){
    // use the content's dimension to obtain the current height of the scroll
    let dimension = this.content.getContentDimensions();

    // scroll to it (you can also set the duration in ms by passing a third parameter to the scrollTo(x,y,duration) method.
    this.content.scrollTo(0, dimension.scrollHeight);
  }
}

1
太好了,谢谢!我该如何进一步修改它以根据搜索栏输入滚动到列表中的特定项目? - Ray Zhang
您是需要在输入时滚动到项目(如自动完成)还是通过单击搜索按钮来查找? - sebaferreras
列表会根据用户输入的搜索栏内容自动过滤,用户可以单击列表项将其保存到购物篮中。然后,搜索栏会自动清除,并重新填充所有可能的项目。但是,在此时,我希望列表也能自动滚动到刚刚单击的项目,以便用户不会因为列表重新填充所有可能的项目而突然感到迷失方向。刚刚单击的项目应该位于搜索栏的正上方(我只能让它滚动到屏幕顶部)。 - Ray Zhang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接