typescript Angular - QueryList ElementRef

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular - QueryList ElementRef相关的知识,希望对你有一定的参考价值。

export class ViewContainerRefWidgetComponent implements OnInit, AfterViewInit {
  allBooks: Book[] = [];
  // selects all 'book' elements from this component
  @ViewChildren('book') books:  QueryList<ElementRef>;

  constructor(private ren: Renderer2) {
  }

  ngOnInit() {
    this.initBooksCollection();
  }
  ngAfterViewInit(): void {
    // here your DOM elements are available
    // you can subscribe to the QueryList and each time an element is added or removed
    // you can see the new QueryList
    this.books.changes.subscribe((val: QueryList<ElementRef>) => {
      console.log(val.toArray());
    });
  }
  filterByGenere(genere: string) {
    this.books.filter(elem => {
      // filters for a speciffic genere
      return this.genereMatches(elem, genere);
    }).forEach(bookNode => {
      // applies CSS to each DOM node
      this.ren.setStyle(bookNode.nativeElement, 'border', '3px solid red')
    });
  }
  addBook() {
    this.allBooks.push({
      id: 'book-6',
      author: 'Stephen King',
      genere: 'fiction'
    })
  }
  genereMatches(element, genere) {
    return element.genere === genere;
  }
  initBooksCollection() {
    return;
  }
}

以上是关于typescript Angular - QueryList ElementRef的主要内容,如果未能解决你的问题,请参考以下文章

Angular 指令依赖注入 - TypeScript

typescript Angular 4基本动画#angular #js

Angular (TypeScript) 模型

如何将变量放入语句 [Angular,TypeScript]

Angular + TypeScript 是否为最佳实践?

Angular 2 Typescript 编译错误