How to call code inside ngAfterViewInit again in angular 2

12,076

Solution 1

You could define an EventEmitter in the constructor, subscribe to it in the ngAfterViewInit() function to update those values, emit it in the ngAfterViewInit() function, and then emit it again every single time you want to call it in subsequent areas of the component. Here is an example:

import { EventEmitter } from '@angular/core';

export class MyComponent implements AfterViewInit {
  public myEvent: EventEmitter<void>;
  
  public constructor() {
    this.myEvent = new EventEmitter<void>();
  }
  
  public ngAfterViewInit(): void {
    // This is how you call the function to do what you want to do with your DOM manipulations below. You can also call this exact function even from the HTML, if you wish to do so (see HTML example).
    this.myEvent.emit();
    
    this.myEvent.subscribe(
      () => {
        // Do whatever actions that you need to do here to perform your DOM manipulations.
      },
      (err: Error) => console.error(err);
    );
  }
  
  public emitMyEvent(): void {
    this.myEvent.emit();
  }
}
<my-component (click)="myEvent.emit()"></my-component>

<!-- or -->

<my-component (click)="emitMyEvent()"></my-component>

Solution 2

If you want to execute those statements on every changes than it is better to write those in ngAfterViewChecked().From the docs:

A lifecycle hook that is called after the default change detector has completed checking a component's view for changes

A callback method that is invoked immediately after the default change detector has completed one change-check cycle for a component's view.

So it will be called on every subsequent changes.

More information can also be found on the Lifecycle Hooks#AfterView docs

Solution 3

If your parameter is available as an Observable, you can just subscribe to it in the ngAfterViewInitmethod. If your parameter is not yet available as Observable, I suggest you take a look at the BehaviourSubject class. With this, you can control when the Observable will emit a new value + It will be triggered with the last value when you subscribe to it

Solution 4

You declare ordinary class methords in the class body, and later define them in the context of ngAfterviewInit. here's a simple use case example:

export class ViewtestComponent implements OnInit, AfterViewInit{
  @ViewChild('someElementMewantedToDoAction') elRef: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  changeVal; 

  ngAfterViewInit() {
    this.changeVal= (useME) => {
      // some action
      this.elRef.nativeElement.innerText++;
    }
   }

Later, use the method in template as

// Do Action=  Button value will increment 11, 12 13 ... on each button   click.

<button class="button success" (click)="changeVal($emit)>10</button>
Share:
12,076

Related videos on Youtube

tsadkan yitbarek
Author by

tsadkan yitbarek

Software Engineering student at AAiT.(programmer)

Updated on June 04, 2022

Comments

  • tsadkan yitbarek
    tsadkan yitbarek almost 2 years

    In my angular component I have ngAfterViewInit method which contains some statements that I want to execute after the view is initialized cause it contains some DOM manupulations.

    My question is when some parameter is changed I want to run the code inside ngAfterViewInit.

    • Günter Zöchbauer
      Günter Zöchbauer about 6 years
      Just move the code to another method that you call from ngAfterViewInit and wherever else you want.
    • tsadkan yitbarek
      tsadkan yitbarek about 6 years
      That code gives me error if the component is not initialized. That's why I put it inside ngAfterViewInit.
    • omurbek
      omurbek about 6 years
    • Günter Zöchbauer
      Günter Zöchbauer about 6 years
      Please post the code that causes the error and the error message.
    • tsadkan yitbarek
      tsadkan yitbarek about 6 years
      @GünterZöchbauer the code uses d3 to draw graph.
  • Sabunkar Tejas Sahailesh
    Sabunkar Tejas Sahailesh over 5 years
    Thank you for your answer, As I was not subscribing my Observable in the ngAfterViewInit() (bcoz- I was using async pipe in template to directly render latest data from server) so my template was not getting updated result.
  • Amit Singh
    Amit Singh almost 3 years
    Using function expression insted of function declaration inside ngAfterViewInit() work well.