角度指令-接触儿童

时间:2019-04-06 18:46:33

标签: angular

假设我有一个父母,并且在内部使用ngFor循环生成了孩子。我想在可访问其所有子项的父项上放置一条指令。

<div appMyDirective>
    <div *ngFor="..."></div>
</div>

如何从该指令(例如QueryList之类)访问所有子级?

注意:插入新的子元素时,我需要保持更新。

@Directive({
   selector: '[appMyDirective]'
})
export class MyDirective {

  constructor(private elem: ElementRef) { }

  // How to access all children (DOM Elements) and stay updated about changes???
}

1 个答案:

答案 0 :(得分:1)

Angular指令不能使用ViewChildViewChildren。 相反,您可以使用指令内的Dependency Injection访问本地dom元素,并使用MutationObserver api侦听更改。例如,请参阅随附的代码段。

Full Example

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appWatcher]'
})
export class WatcherDirective {
  observer
  constructor(private elem: ElementRef) {
    console.log('Watcher Attached', elem)
  }

  ngOnInit() {
    var observerOptions = {
      childList: true,
      attributes: true,
      subtree: true //Omit or set to false to observe only changes to the parent node.
    }
    this.observer = new MutationObserver(this.callback);
    this.observer.observe(this.elem.nativeElement, observerOptions);

  }

  private callback(mutationList, observer) {
    mutationList.forEach((mutation) => {
      switch (mutation.type) {
        case 'childList':
          /* One or more children have been added to and/or removed
             from the tree; see mutation.addedNodes and
             mutation.removedNodes */
          console.log('Child Added or removed');
          break;
      }
    });

  }
  ngOnDestroy() {
    this.observer.disconnect();
  }

}