Examining the status of child components in Angular

Within my codebase, there exists a Parent component that contains multiple instances of the Child component. Each child component dynamically decides whether or not to render its content based on various user settings and other factors.

In the HTML file of parent.component:

<h1 *ngIf="(activeX || activeY || activeZ)">Hello, get started!</h1>

<app-get-started-X [(active)]="activeX">
</app-get-started-X>

<app-get-started-Y [(active)]="activeY">
</app-get-started-Y>

<app-get-started-Z [(active)]="activeZ">
</app-get-started-Z>

In the TypeScript file of parent.component:

...
activeX: boolean;
activeY: boolean;
activeZ: boolean;
...

In the HTML file of get-started-X.component:

<ng-container *ngIf="active">
    <h2>Get stared with X tutorial</h2>
    Lorem ipsum...
</ng-container>

In the TypeScript file of get-started-X.component:

...
@Input() active: boolean;

@Output() activeChange: EventEmitter<boolean> = new EventEmitter();
...

ngOnInit(): void {
    this.active = false;
    this.activeChange.emit(false);

    forkJoin([
        this.settingsStorage.get<boolean | undefined | null>(
            KEY_ORG_APP_DESIGN_LAYOUT_SELECTED
        ),
    ])
        .pipe(
            finalize(() => {
                this.cdr.markForCheck();
            })
        )
        .subscribe(([setting]) => {
            this.active = (setting !== undefined && setting != null) ? setting : true;
            this.activeChange.emit(this.active);
            this.cdr.markForCheck();
        });
}
...

Answer №1

ngOnInit(): void {
        setTimeout(() => {
            this.cdr.markForCheck();
        }, 10);
    }

Allow me to provide you with a comprehensive explanation of why this particular piece of code functions correctly, while yours may not.

First and foremost, it is crucial to understand the concept of ZoneJS.

ZoneJS can be likened to a "signal emitter" - essentially, its role is to monitor the execution of functions, detect their initiation and completion, and emit events to prompt certain observers.

Within Angular, ZoneJS operates behind the scenes, making its operation seamless to developers who are just starting out with the framework.

A notable aspect of ZoneJS is its ability to perform monkeypatching - essentially modifying native JS functions to fulfill its intended purpose.

An interesting way to observe this in action is by running:

console.log(setTimeout);

In a traditional JavaScript environment, you would typically see [native code]. However, in an Angular context, a custom function reflecting ZoneJS's influence will be displayed.

This behavior extends to various methods such as timeouts, internal operations, and animation frames.

The reason the provided code works effectively is that once the timeout concludes, ZoneJS alerts Angular that your code has finished executing, prompting Angular to trigger a change detection. This mechanism underlies the success of your code.

In contrast, when manually marking your component for detection, you simply indicate that it should be considered during the next occurrence of change detection rather than triggering the process immediately.

Regrettably, RxJS does not integrate seamlessly with ZoneJS, meaning that occurrences like .subscribe do not trigger detections, particularly problematic when utilizing the onPush change detection strategy.

To address this issue, consider replacing markForCheck with detectChanges, or utilize a component variable accessed in your HTML using the | async pipe, which inherently triggers a change detection cycle.

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

Adding elements to a page while it is running can be achieved using a variety

Working on a college project, I am developing a demo web-app in Angular. The goal is to implement a feature where clicking a button adds a new node to the DOM tree. In JavaScript, a simple solution would be: document.getElementById('ticket-container& ...

Can a TypeScript variable in Angular contain a mixture of HTML and plain text?

I have a website where I am displaying content from a Model file. I would like to create a TypeScript variable that contains both a string related to the website's content and a URL enclosed in an HTML tag. When this variable is rendered on the view, ...

Having trouble navigating to a child page in Angular 4

When I try to follow the Angular routing & navigation example, I encounter an issue where my page displays as "file not found" when I route. Even when I navigate to the profile page at profile.component.html, I can see my columns, but nothing appears from ...

Debugging with Android deep links

Currently, I am facing a challenge with my Ionic Angular application. It involves directing users to a browser for authentication via Auth0 and then redirecting them back to the application. However, the redirection is not happening due to the lack of deep ...

Guide on utilizing the chosen dropdown field across multiple components

I am looking for a solution to share the chosen value with all components, allowing it to be accessed whenever needed. ...

What causes a boolean to evaluate to true?

Check out this code: export class Smth { private flag: boolean; public update() { this.flag = true; this.inner(); if (this.flag === false) { // Operator '===' cannot be applied to types 'true' and 'false'. ...

Protecting NestJS API for Angular App with Auth0

Currently, I am working on an Angular application that utilizes NestJS as the backend. Authentication is functioning properly in the Angular app, where users can log in to Auth0 and are redirected back to our app seamlessly. The /token call in the network ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...

Inkwell shifts bespoke quality

I am currently utilizing Quill (v.2.0.0) with quill-better-table (v.1.2.10) within my Angular 13 project. I am attempting to incorporate a custom attribute to the table tag, as shown below: <table class="quill-better-table" custom-attribute=& ...

The jquery ui slider in Angular is not triggering the function when changes are made to the slider

I'm currently using Angular with jQuery UI slider and I have successfully initialized the slider and it is functioning properly. However, when I try to call another function from the change event, I encounter an error message: TypeError: this.getSe ...

Is it possible for a factory provider to include optional dependencies?

As an illustration: @NgModule ({ providers: [ { provide: MyService, useFactory: (optionalDependency) => new MyService(optionalDependency) deps: [ANOTHER_DEP] } }) class MyModule {} Is it possible for useFactory to include optio ...

How to manage type mappings while utilizing the spread syntax

In my testing scenario, I am utilizing a setup function and I am looking for a way to pass typing information along when it is called so that I can benefit from intelligence support without having to bypass it in eslint. function setup(): SomeType { retu ...

How can we avoid printing out undefined data from an Observable in Angular 2?

Here is the code I have in my service: fetchUserData(userId: string): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/todos/' + userId) .map((response: Response) => { const userData = ...

Setting up in the namespace for typescript

Is there a way to assign to namespaces using dot notation like this? namespace item {} item.item1 = { name: "Some Item" } item.item2 = { name: "Some Item" } An error is thrown with: Property 'item1' does not exist on ty ...

"Implementing a date picker in your Ionic 5 app: A step-by-step

How can I integrate a date picker similar to the Angular Material Date picker into my Ionic 5 application? I prefer not to use the native ion-datetime component due to limitations such as incomplete calendar display and lack of support for alternative ca ...

How can we utilize Typescript to check if the intern 4 page has finished loading?

I've managed to set up a function in intern 4 using TypeScript that waits for the page to load. However, there are instances where it doesn't work and throws a TimeOutError even when I catch the error within the function. Can someone please take ...

I have successfully implemented useLazyQuery in a functional component, but now I am looking to integrate it into a class component. Can you provide guidance on how to achieve

Recently, I encountered an issue with my functional component that contains 3 checkboxes and 1 button. I utilized the useLazyQuery hook to ensure that my query was only sent upon clicking the button. However, a major drawback is that my component re-rend ...

Encountered an error while trying to access the 'deletePostById' method in Angular due to undefined properties

Help needed: TypeError regarding 'deletePostById' What's causing the issue in my code? HTML <div class="row post" *ngFor="let post of posts"> <div *ngIf="isAdminIn" ngbDropdown class="float- ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

What is the best way to compare input to 2 distinct patterns in order to produce 2 separate error messages accordingly?

Is there a way to use HTML and angular to validate input against two patterns and generate two different inline error messages? The "pattern" attribute in the input tag doesn't seem to work for this. For instance, I need to validate if the input star ...