需要延迟加载 mat-accordion 内容的帮助

need help w/ lazy loading mat-accordion content

我正在使用 Angular 5 和 mat-accordion 来显示作者列表。每个作者都写过多本书和文章。作者的名字出现在 panel-header 面板的内容显示所有的书籍、文章等

因为我想显示 100 多个作者,每个作者都有 50 多个条目,所以我不想一次填充整个手风琴和内容。我希望发生的事情是,当用户单击作者时,它会启动查询数据库的服务,然后根据需要填充面板内容。如果面板关闭,内容应该保留,这样 re-expanding 面板就不会启动另一个数据库查询。

因此,当我访问该页面时,我看到了作者 Alice、Bob 和 Eve。当点击 Alice 时,应用程序查询数据库,取回 Alice 的条目,呈现内容,然后手风琴展开。当我点击 Eve 时,应用程序应该关闭 Alice 的面板,查询数据库,获取 Eve 的条目,呈现内容,最后展开面板。

如果我再次单击 Alice,Eve 的面板将关闭,但由于 Alice 的内容已经存在,因此没有数据库查询或渲染。它只是扩大。文档说要使用 ng-template,但我不确定该怎么做,而且真的不确定该怎么做,以便在面板关闭后内容仍然存在。我不担心数据发生变化需要再次获取爱丽丝的数据以防发生变化。

有没有关于处理此问题的最佳方法的示例?

谢谢!

G。 Tranter 的回答是正确的,我走在正确的道路上。如果其他人最终出现在这个页面上,这就是我最终所做的。

ngOnInit(){ 
    this.authorsRetrieved.subscribe( authors => {
        this.allAuthors = authors as Array;
        this.authorsRetrieved = new Array(
            Math.max.apply(Math, this.allTrainers.map(function(t){ return t.trainer_id; }))
        );
// as authors are added and deleted, the author_id won't equal the number of 
// authors, so get the highest id number, create an array that long
// then fill it with blanks so the keys have some value
            this.authorsRetrieved.fill([{}]);
        });

showAuthorsWorks(authorID: Number = -1){
    if(authorID > this.authorsRetrieved.length){
      const tempArray = new Array(authorID - this.authorsRetrieved.length + 1);
      tempArray.fill([{}]);
      this.authorsRetrieved = this.authorsRetrieved.concat(tempArray);
    }
// only make the network call if we have to
// because we filled the id array, we can't just use length
if(typeof(this.authorsRetrieved[authorID][0]['manuscript_id']) === 'undefined'){
  this.authorWorksService.getAuthorWorks(authorID).subscribe( works => {
    this.worksRetrieved.splice(authorID, 0, works as Array<any>);
  });
}

我为数组长度小于最大值 author_id 的几乎不可能的情况添加了检查。您必须创建一个包含 N 个元素的空数组,然后填充该数组。如果不这样做,空数组的长度为0,就不能向不存在的数组元素中压入数据。即使在 chrome 控制台它说长度是 N 并且元素在那里,只是空的。

再次感谢!

如果您指的是与 ng-template 一起使用的 MatExpansionPanelContent 指令,它所做的只是延迟加载内容,直到面板打开。它不知道它是否已经加载。因此,如果您对 {{lazyContent}} 等内容使用绑定表达式,每次打开选项卡时都会对其进行评估。您需要自己管理内容缓存。一种简单的方法是通过 getter.

在你的组件中:

_lazyContent: string;
get lazyContent() {
    if (!this._lazyContent) {
        this._lazyContent = fetchContent();
    }
    return this._lazyContent;
}

加上你的HTML:

<mat-expansion-panel>
    ...
    <ng-template matExpansionPanelContent>
        {{lazyContent}}
    </ng-template>
    ....
</mat-expansion-panel>

所以 ng-template 负责延迟加载,getter 负责缓存内容。