在视图上加载数据后触发函数 angular 7

Trigger a function after data is loaded on the view angular 7

我是 angular 的新手,只是想掌握它。我有一个显示商店商品的页面

<div *ngIf="products" class="col-lg-12">  
  <div *ngFor="let prod of products.data" class="col-lg-3 cont" cdkDrag>
    <div class="col-sm-offset-2 col-sm-8 productItem">
      <p class="text-center">
        <img src="https://www.classicposters.com/images/nopicture.gif" width="125" height="160" />
      </p>
      <p>
        <i>{{prod.title}}</i>
        <br />
        <i >{{prod.price | currency:"£"}}</i>
      </p>
    </div>
  </div>
</div>
<div *ngIf="products" class="row">
  <div class="col-lg-12 text-center">
     Page {{products.pageOn}} of {{products.totalPages}}
  </div>  
</div>

如果产品数组有值,则加载它们。将加载不透明度 0,然后将一个接一个地加载。我需要在触发偶数之前触发内容加载完成时的功能。

我的 .ts 中有 ngOnInit() - 这会创建数据订阅 return 并将其放入产品数组(在视图中使用) - 数据源作为 2 秒休眠它代表缓慢的加载时间。

ngOnInit() {
    this.data.getProducts(1).subscribe(prods => {
      this.products = prods;
    });
    console.log('on init: ' + Date().toString());
  }

我尝试挂钩订阅者的调用,但没有用,然后我看到了生命周期挂钩。我尝试了 AfterViewInit 和 AfterContentInit,但两者都不满意。

我将如何监听页面(包含数据)在触发函数之前完成加载?

是否有任何资源可以帮助我找到此类问题?

谢谢 马克

编辑: 我将其更改为使用 [hidden] 样式,然后我可以使用 AfterViewInit 来触发动画循环。但是,我收到一个错误,它在未初始化时尝试使用 products.data。似乎 *ngIf 使 AfterViewInit 能够很快触发

<div [hidden]="!products" class="col-lg-12">  
      <div *ngFor="let prod of products.data" class="col-lg-3 cont">

这是一个 Stackblitz demo 和 angular 动画:

这是关于动画的some doc(@markblue777 指出)。

容器元素包装由 ngFor 标记的项目列表。容器元素包含一个动画触发器 [@listAnimation],它被设置为查询每个内部项目。

项目按顺序添加有延迟,不透明度淡入动画运行。

<div *ngIf="products" class="col-lg-12" [@listAnimation]="items.length">  
  <div *ngFor="let prod of items" class="col-lg-3 cont" cdkDrag>
    <div class="col-sm-offset-2 col-sm-8 productItem">
      <p class="text-center">
        <img src="https://www.classicposters.com/images/nopicture.gif" width="125" height="160" />
      </p>
      <p>
        <i>{{prod.title}}</i>
        <br />
        <i >{{prod.price | currency:"£"}}</i>
      </p>
    </div>
  </div>
</div>
<div *ngIf="products" class="row">
  <div class="col-lg-12 text-center">
     Page {{products.pageOn}} of {{products.totalPages}}
  </div>  
</div>
import { Component, OnInit } from '@angular/core';
import {
  trigger,
  style,
  query,
  stagger,
  animate,
  transition,
} from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
  trigger('listAnimation', [
    transition('* => *', [
      query(':enter', [
        style({ opacity: 0 }),
        stagger(100, [
          animate('0.5s', style({ opacity: 1 }))
        ])
      ], { optional: true })
    ])
  ])
  ],
})
export class AppComponent implements OnInit  {
  products = { pageOn: 0, totalPages: 5, data: null };
  items = [];

  ngOnInit(): void {
    this.apiCall().then(products => {
      this.products = products;
      // We then animate the entry of each item separately
      products.data.forEach((product, idx) => {
        setTimeout(() => {
          this.items.push(product);
        }, 500 * (idx + 1)); // Each item is inserted 500ms after the last one.
      });
    });
  }

  // Simulate the API call
  apiCall(): Promise<any> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ pageOn: 0, totalPages: 10, data: [
          { title: 'cheese', price: 1 },
          { title: 'chothes', price: 2 },
          { title: 'Food', price: 3 },
        ]});
      }, 2000); // with a delay of 2000ms
    })
  }
}

您必须添加 BrowserAnimationsModule 才能正常工作:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

我对你的问题的理解是你想要一个函数来 运行 当页面完成绘制时。

尝试注入文档并将其转换为可观察对象。我还没有玩过所有的可能性,但是当 ngoninit 完成时会发生这种情况。另一种解决方案是将其放入 promise 块中。

private documentDone: Observable<any>
constructor(
@Inject(DOCUMENT) private document: any){}

ngOnInit(): void {
this.documentDone = fromEvent(this.document, 'readystatechange');
this.documentDone.subscribe(state => console.log('im done');
}