How to detect when Angular has attached elements to the DOM?

前端 未结 3 1502
情深已故
情深已故 2021-01-15 17:22

There is a component:

it\'s component receives a stream of numbers as @Input

3条回答
  •  终归单人心
    2021-01-15 17:41

    You can create a directive to detect the elemntmrender to the dom and run a method at that time

    import { Directive , Output ,EventEmitter } from '@angular/core';
    
    @Directive({
      selector: '[rendered]'
    })
    export class RenderedDirective {
    
       @Output() rendered:EventEmitter = new EventEmitter();
    
       ngAfterViewInit() {
         this.rendered.emit()
       }
    
    }
    

    ngAfterViewInit will called after Angular has fully initialized a and render li elemnt

    MyComponent

    export class MyComponentComponent {
    
      numbers: number[] = [];
    
      @Input() set data(numbers: number[]) {
        this.numbers = numbers;
      }
    
      myCallback(elm) {
        console.log(elm)
      }
    
    }
    

    template

    • {{n}}

    stackblitz demo

提交回复
热议问题