簡體   English   中英

我無法訪問我使用 ngFor 循環創建的 DOM 元素,並且我正在從服務中獲取數據。 Angular

[英]I am not able to access DOM element which I am creating using ngFor loop and I am getting the data from the service. Angular

我在 angular 中遇到了與 DOM 操作相關的問題。 我在我的組件中定義了一個名為 colors 的數組,然后我調用服務方法並從服務器獲取 colors 數據,然后將它們分配到訂閱方法中的 colors 數組中。 在使用 *ngFor 循環的 HTML 模板中,我正在顯示 colors 數組數據。 現在我想向 HTML 元素添加一些動態 class 或樣式,為此,我使用 ElementRef 訪問此元素,但我無法訪問它,因為 colors 數組最初是未定義的。 現在讓我附上代碼...

@Component({
  selector: 'app',
  template: "<div><li class="color" *ngFor="let color of colors">{{color}}</li></div>",
  styleUrls: ['./app.component.css'] 
})

export class AppComponent implements OnInit, AfterViewInit {
   colors:any;

   constructor(private elementRef:ElementRef, private renderer:Renderer2) {}
   
   ngOnInit():void {
     setTimeout(() => {
        this.colors = ['red', 'yellow', 'green'];
     }, 1000);
   }

   ngAfterViewInit():void {
     const color = this.elementRef.nativeElement.querySelectorAll('.color');
     console.log(color);
   }
}

在這里,我在此代碼中使用 setTimeout function,它的行為類似於服務,因為該服務需要一些時間從服務器獲取數據,但在我的代碼中,我使用的是服務。

現在,如果我在開發人員工具中打開控制台,那么我會得到 NodeList [],這意味着我無法訪問 DOM 元素。 我知道我無法訪問 DOM 元素的問題,因為我的訪問 DOM 元素的代碼在分配給 colors 數組的數據之前運行,默認情況下或最初 colors 數組未定義或為空。 這就是我在控制台中獲取 NodeList [] 的原因。 但我無法理解如何解決這個問題?

提前致謝。

你需要ngAfterViewCHecked 這將在每次 Angular 完成對組件及其子組件的更改檢測時運行

其次, template有錯誤。 如果您使用所有雙引號"將終止字符串。您不需要對這樣的所有屬性使用單引號和雙引號

'<div><li class="color" *ngFor="let color of colors">{{color}}</li></div>'

演示

這是因為ngAfterViewInit在您在ngOnInit中設置的超時完成之前調用。

我會 go 使用更可靠的ViewChildren方法。
這是一個例子:

@Component({
  selector: "my-app",
  template: `
    <ul>
      <li #color *ngFor="let color of (colors$ | async)">{{ color }}</li>
    </ul>
  `,
  styles: []
})
export class AppComponent implements OnDestroy, AfterViewInit {
  @ViewChildren("color") colors: QueryList<ElementRef<HTMLLIElement>>;
  colors$: Observable<string[]> = of(["red", "green", "blue"]).pipe(
    delay(3000)
  );

  private colorsSubscription = Subscription.EMPTY;

  ngAfterViewInit(): void {
    this.colors.changes.subscribe(list => {
      list.forEach(element => {
        console.log(element.nativeElement);
      });
    });
  }

  ngOnDestroy(): void {
    this.colorsSubscription.unsubscribe();
  }
}

我們在這個例子中所做的是:

  • 初始化colors$以在 3 秒后觸發字符串數組
  • 使用AsyncPipe訂閱colors$並顯示 colors
  • ViewChildren設置為使用#color模板參考查詢所有元素
  • 訂閱QueryList更改(添加/刪除等)並采取相應措施

你可以在這個 stackblitz中找到完整的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM