Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit:

@Input 
public stringArray: string[];
public newArray: string[];

ngAfterViewInit() {
  this.newArray = this.stringArray.filter(x => x.includes('a'));
}

I placed the code inside ngAfterViewInit to ensure that it waits for @Input properties to be initialized.

However, upon execution, it appears that the code within ngAfterViewInit is 'undefined.'

How can I ensure that all @Input properties are fully initialized before executing the filter operation?

UPDATE: Although the @Input property does contain data eventually, it occurs after ngAfterViewInit. How can I guarantee that my code only runs once all @Input() properties are fully initialized?

Answer №1

Transfer your code to ngOnChanges method.

ngOnChanges(changes: SimpleChanges) {
    if(changes && changes.stringArray.currentValue && !this.newArray) {
       this.newArray = this.stringArray.filter(x => x.includes('a'));
    }
  }

This adjustment is necessary because the property was still changing in the parent component even after the child component had been initialized.

Answer №2

One approach to consider is utilizing a setter function and bypassing the need for ngAfterViewInit().

public filteredArray: string[];

@Input
set inputArray(value: any) {
  this.filteredArray = value.filter(item => item.includes('a'));
}

Answer №3

In the main component, include the following code:

<div *ngIf='stringArray.length > 0'>
<child-component [stringArray]='stringArray' ></child-component>
</div>

This means that the child component will only be initialized if there is data in the input properties provided.

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

Controller property not being updated by directive

I have developed a custom directive to identify when the enter key is pressed within a text box. Here's the implementation of the directive: import { BookmarkService } from "../services/bookmarkService"; import { qlik, QlikBookmarkInfo } from "../qli ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

release a Node.js module on NPM

Being a complete beginner in creating npm packages using typescript2 and angular2, I find myself in need of creating an npm package and publishing it on our company's private repository. I've managed to generate files like d.ts and .js. But how ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Tips on assigning array union as the return type of a function

I am working with a function parameter that accepts an array union, like this: (ClassA|ClassB)[]. How can I return either ClassA[] or ClassB[] from the function? When attempting to return type (ClassA|ClassB)[], I encounter the following error: Assig ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

what is the reason for why the subscribe method returns a Subscriber instead of the actual value

Within my application, User configurations are retrieved based on a config ID that is stored in the node server. exports.getConfig() = (req, res) => { return res.status(200).send(id); // where id is sourced from a configuration file } In my service ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

Font loading error in Angular 2 - Denied access to load font

Recently, I started experimenting with Angular 2 and delved into working with routes. Surprisingly, everything was functioning seamlessly until I introduced routes into the mix. Now, whenever I navigate to /home, an error pops up. Refused to load the font ...

What is causing the memory leak in this code snippet?

While working with the http service to retrieve user data from UserService, I encountered a memory leak issue. Upon subscribing to the observable, an infinite number of http requests are being triggered as shown in the network tab of the developer console. ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Typescript - Defining string value interfaces

I have a property that can only be assigned one of four specific strings. Currently, I am using a simple | to define these options. However, I want to reuse these types in other parts of my code. How can I create an interface that includes just these 4 va ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

The class-transformer malfunctioning: The transformation function is not being executed

I am facing an issue with implementing class-transformer in my codebase, despite using type-graphql and @typegoose/typegoose libraries. Below is the snippet of my code: Custom Decorator import { Transform } from 'class-transformer'; export func ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Warning: The use of the ngModel input property and ngModelChange event with reactive form directives has been marked as obsolete

Encountered the following error: It seems that the usage of ngModel alongside formControlName on the same field is deprecated in Angular v6 and will be removed in Angular v7. After attempting to address this issue by removing "[ngModel]="value"", the pro ...

By default, the ejs-datetimepicker in @syncfusion/ej2-angular-calendars will have an empty input field

I incorporated a datetime picker from @syncfusion/ej2-angular-calendars into my project. However, I noticed that the datetime picker displays the current date and time by default in its input field. Instead, I would like the input field to be empty when ...

Please ensure that the Angular Input field only allows for numbers to be entered, with the exception that the

My input should only allow numbers, with the exception of the first digit being zero. I have attempted to use regex in this directive, but it is not functioning as expected. import { Directive ,ElementRef, HostListener} from '@angular/core'; @Di ...