The custom component is not updating the NgIf directive in HTML even though it receives a boolean variable

I am struggling with a custom component that includes an *ngIf in its view to handle a boolean variable, but for some reason the *ngIf directive is not working. Here is the code snippet:

Component

@Input('title') titleText;
@Input('backButton') backButton;
@Input('avatarImage') avatarImage;
@Input('userId') userId;
@Output('avatarClicked') avatarClicked = new EventEmitter()

titlePage: string;
img: string; 
back: boolean = false;

constructor() {}

ngAfterViewInit() {
    this.titlePage = this.titleText;
    this.img = this.avatarImage;    
    this.back = this.backButton;    
}

openPersonalData() {
    this.avatarClicked.emit({value: this.userId})
}

Component HTML

<ion-header>
    <ion-toolbar>        
        <ion-buttons *ngIf="back == true" slot="start">
            <ion-back-button text="Voltar"></ion-back-button>
        </ion-buttons>
        <ion-title>{{ titlePage }}</ion-title>        
        <ion-avatar slot="end" (click)="openPersonalData()">
            <img [src]="img">
        </ion-avatar>
    </ion-toolbar>
</ion-header>

Page using the component

<app-header title="Chat" 
    [backButton]="true" 
    avatarImage="{{ user[0].img }}" 
    userId="{{ user[0].id }}" 
    (avatarClicked)="openPersonalData($event)">
</app-header>

Any insights on what might be causing this issue would be greatly appreciated.

Answer №1

This particular piece of code is functioning correctly and implements the necessary logic:

To see it in action, please refer to this link: (simply adjust the value of [backButton]="true" to [backButton]="false" to observe whether the son element is displayed or not)

PARENT HTML:

<app-header
  title="If you see this, backButton is set to true"
  [backButton]="true"
>
</app-header>

SON HTML:

<div *ngIf="backButton">
  {{ title }}
</div>

SON COMPONENT TS:

import { Component, Input } from "@angular/core";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: []
})
export class HeaderComponent {
  @Input("title") title;
  @Input("backButton") backButton;
}

Answer №2

It appears that your input is being updated following the ngAfterViewInit lifecycle hook. Additionally, there seems to be unnecessary duplication in reassigning a field. To streamline your code, consider directly utilizing the backButton input within your template.

<ion-buttons *ngIf="backButton == true" slot="start">

Answer №3

In my opinion, it would be beneficial to manipulate your data values within the ngOnChanges lifecycle method:

// Executed whenever there are changes in component @Inputs

@Input('title') titleText;
@Input('backButton') backButton: boolean;
@Input('avatarImage') avatarImage;
@Input('userId') userId;
@Output('avatarClicked') avatarClicked = new EventEmitter()

titlePage: string;
img: string; 
back: boolean = false;

constructor() 




   ngOnChanges () {
        // Ensure that data is available before processing
        if (this.backButton) {
             this.back = this.backButton; 
        {
    }

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

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

What is the process for setting the active state for HtmlBodyElement?

I attempted to use the following method: document.querySelector('body').setActive(); However, I encountered an error: TS2339: Property 'setActive' does not exist on type 'HTMLBodyElement'. Any suggestions on how to resolve t ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

Transmit a form containing a downloaded file through an HTTP request

I am facing an issue with sending an email form and an input file to my server. Despite no errors in the console, I can't seem to upload the file correctly as an attachment in the email. post(f: NgForm) { const email = f.value; const headers = ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

Accessing Angular's Observable Objects

I am currently in the process of learning Angular and trying to work with Observables. However, I am facing an issue where I cannot extract data from an Observable when it is in object form. public rowData$!: Observable<any[]>; UpdateGrid() { this ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

I prefer not to run the next.js SWR until after the initial rendering

Development Setup ・ next.js ・ typescript ・ swr This uses swr for communication purposes. I am looking to only trigger it when the query value changes. However, it is also being executed during the initial rendering. How can I prevent it ...

Swagger is refusing to cooperate because my model's attributes are set to true

Currently delving into Swagger and its documentation functionality through a YAML file. Previously, I had used @swagger in the controller file and everything worked fine. However, when attempting to transition to a YAML file for better organization, issues ...

Transmit data to a modal popup in Angular 8

Here is the code snippet written in .ts file: openFormModal(id: number) { console.log(id); const modalRef = this.modalService.open(PartidoComponent); modalRef.componentInstance.id = id; //modalRef.componentInstance.id = id; modalRef.r ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

When using the async pipe with Angular's ngFor, an error message indicates that the argument is

Can you explain why this error message is appearing: Argument of type '[string, { startTime: string; endTime: string; }][] | null' is not assignable to parameter of type 'Collection<unknown>'. It occurs when attempting to utilize ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

Instructions on resolving the issue: The type 'string | ChatCompletionContentPart[] | null' cannot be assigned to type 'ReactNode'

I've been working on my first Saas App, similar to a ChatGPT, using NextJs with the OpenAI Api. Most of the development was based on a YouTube tutorial until I encountered two errors caused by an update in the OpenAI version. Despite trying various so ...

Guide for setting up various validations for formGroup in an Angular 5 project

I am currently working on implementing Angular reactive form validation. My existing structure only includes validation for required fields, but I am looking to add additional validations such as minLength, email, and postcode. One challenge I face is cre ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

Scrollable Turbo Table experiencing a problem with the PrimeNG filter dropdown

When using PrimeNG Turbo Table, I am facing an issue where the filter dropdown is getting placed inside the scrollable table. The dropdown works perfectly fine without the scrollable table. You can see it in action here. However, when the table is scroll ...