首页 > 解决方案 > 在 Angular 组件 ngAfterViewInit 中定位 DOM 元素返回空 nodeList

问题描述

所以,我有一个服务,里面有返回承诺的方法。在我的component.ts文件中,我正在注入服务,然后尝试在 a 中调用它的方法,Promise.all([])因为在渲染视图之前我需要服务的所有结果。

我这样做的方式是通过*ngIf模板的容器元素上的指令来检查服务的结果是否全部返回(通过一个名为 的变量pageReady),然后呈现模板。

我的 component.ts 文件...

import { Component, OnInit, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
import { MyService } from './services/myservice.service';

@Component({...})

export class MyComponent implements OnInit, AfterViewInit {
    public pageReady: Promise<boolean>;
    public items;
    public items2;
    public nodelist;

    constructor( private service: MyService, private el: ElementRef ) { }

    ngOnInit() {
      this.fetchData();
    }

    /* This right here is my problem */
    ngAfterViewInit() {
      this.nodelist = this.el.nativeElement.querySelectorAll('.items figure');
      console.log(this.nodelist);
    }

    private getFirstItem() {
      return this.service.serviceMethodOne(); /* Returns promise */
    }

    private getSecondItem() {
      return this.service.serviceMethodTwo(); /* Returns promise */
    }

    private async fetchData() {
       return await Promise.all([this.getFirstItem(), this.getSecondItem()]).then(res => {
          // Assign returned values to class variables that will be used in the template
          this.items = res[0];
          this.items2 = res[1];

          this.pageReady = Promise.resolve(true);  
       });
    }
}

模板文件...

<div class="container" *ngIf="pageReady | async ; else loading">
   <section class="items">
      <figure *ngFor="let item of items">
         <img src="{{ item.path }}" alt="{{ item.title }}">
      </figure>
   </section>

   <section class="items2">
      <div class="item2" *ngFor="let item2 of items2">
         <p>{{ item2.name }}</p>
      </div>
   </section>
</div>

<ng-template #loading>Loading...</ng-template>

我需要操作内部定位的 DOM 元素,ngAfterViewinit但它返回一个空的 nodeList。其他一切正常,我取回所有数据,<ng-template>Loading</ng-template>然后显示按预期消失。我需要知道如何成功定位那些 DOM 元素。

任何帮助将不胜感激。

标签: angular

解决方案


推荐阅读