Executing a function once the Angular Component's DOM has been updated, just like how ngAfterViewInit works

I have a unique feature in my component that creates multiple directives based on user input. The simplified example below demonstrates how the component receives configuration data through an Input(), processes it using a service called MyService to generate this.fields, and then uses the dynamicField directive to display the fields within the component. After all the fields are generated by the directive, I need to execute doSomething(). I achieved this by utilizing ngAfterViewInit(), which functions effectively.

However, I encounter a challenge: at a later stage, I wish to update this.fields as some components are removed and new ones are added dynamically. How can I re-run doSomething() after all the directives have been re-rendered? In such cases, ngAfterViewinit() fails to trigger.

import { MyService } from './myService.service';

@Component({
    selector: 'mycomp',
    template: '<ng-template *ngFor="let field of fields;" dynamicField [config]="field"></ngtemplate><button (click)="myTrigger()">Trigger</button>'
})
export class MyComponent implements AfterViewInit, OnInit{

    @Input() config: object;
    fields: object[];

    constructor(myService: MyService){
    }

    ngOnInit(){
        this.fields = this.myService.getFields(this.config);
    }

    myTrigger(){
        this.fields.pop();
        this.fields.push({'id': 'someotherfield', 'label':'someotherfield'})
    }

    doSomething() {
        console.log('dosomething');
    }

    ngAfterViewInit(){
        doSomething();
    }
}

Answer №1

Consider implementing a delay in execution by using setTimeout for the next tick:

executeAction(){
  this.items.remove();
  this.items.add({'id': 'anotheritem', 'label':'anotheritem'})
  setTimeout(() => {
    this.performTask()
  })
}

Answer №2

Here's a suggestion:

import { Component, AfterViewChecked, OnInit} from '@angular/core';


export class MyComponent implements AfterViewChecked, OnInit{


     ngAfterViewChecked(){
         performAction();
     }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Amazon IVS Player within Angular

Struggling to integrate the npm version of the amazon-ivs-player with Angular, as it seems optimized for webpack while I am using angular-cli. Following a guide at this link. The issue arises with importing the wasm files in my Angular application: ERROR ...

Can you explain the process of retrieving data from a Material 2 table?

In my Angular 2 application, I am utilizing a Material 2 table to showcase items and their corresponding data. Each row in the table has an edit button on the right side, which triggers the appearance of input fields populated with the values of that speci ...

A guide on leveraging typeof within function parameters to ensure accurate variances

Let's create a simple class hierarchy and a list of instances. The goal is to filter items from the list of instances based on their class. There are a couple of challenges: We cannot use the typeof T syntax. How can this be written? We cannot decla ...

What sets the do/tap operator apart from other observable operators?

Can anyone clarify the distinction in simple terms between the typical observable operators used for observing output and why do/tap appear to serve the same purpose? What is the reason for utilizing do/tap? ...

Mastering the Art of Handling Postgres Error Messages for Accurate Query Execution

Currently, I am utilizing pg and node.js. The issue arises when a user logs in through the auth0 widget, as I am passing the returned email to check against my database for existing users. If the user does not exist, I am inserting their information into t ...

Why is Angular.orderBy not displaying any data on the Page?

Embarking on my first Angular project with Firebase Firestore, I am excited to showcase some of the code below. I recently learned Angular and here is what I have accomplished so far: Component.html <section class="rank"> <p class=& ...

What strategies can I implement to reduce the size of my Angular application to 500K or less?

I have been researching ways to reduce the size of my Angular application, but have not yet found a solution that significantly decreases its size. Currently, my application is 4M in production and 14M in development. So far, I have tried: Lazily loadin ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

Modify the value of mat-slide-toggle from TypeScript code

This is the HTML code I have for a mat-slide-toggle element, with a toggleStatus() function: <span class="form-control form-control-plaintext"> <mat-slide-toggle name="status" checked="" ...

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...

Ways to make the current day stand out in a date picker calendar

Utilizing the ng-bootstrap datepicker, I am attempting to showcase an inline calendar in my application. However, the calendar fails to display the current day correctly, as depicted below: https://i.sstatic.net/KVhas.png Despite trying various solutions ...

Is there a way to modify the default lite-server port in the Angular quickstart setup?

I recently obtained the Angular 4 quickstart app and decided to modify the default lite-server port by including "port": 8000 in bs-config.json like this: { "server": { "port": 8000, "baseDir": "src", "routes": { "/node_modules": "node ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

What are the steps for deploying an Angular 6 application on an Express server?

In my express server.js file, I have the following line of code: app.use(express.static(path.join(__dirname, '/dist/'))); This line is responsible for serving up the Angular app when users navigate to /. However, if the app has additional route ...

Is it possible for me to transition to working with Angular 8 after mastering Angular 4?

After mastering Angular 4, I'm interested in knowing the key distinctions between it and Angular 8. What new concepts or features do I need to familiarize myself with beyond what I already know from Angular 4? Thank you for your help. ...

Steps to convert a value to currency pipe after encountering an error message in Angular 8

When using the currency pipe in the blur event, it works correctly initially. However, if an error message for validation is received and some numbers are deleted, the input does not reformat to the currency format as expected. For example, entering the nu ...