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

Include a Custom Button with an Optional Event Handler

I've created a customized material-ui button component: type ButtonProps = { disabled: boolean; text: string }; export function CustomButton({ disabled, text }: ButtonProps) { return ( <Button type="submit" disabled={disabled} ...

Dynamically generating PWA manifests in Angular 7

I just finished building a Progressive Web App (PWA) using Angular 6. Now, I am looking to customize the icons and start URLs dynamically because the app will be accessed through different URLs, each with its own unique logo assigned to it. Is there a way ...

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

How can I disable AngularJS code completion/suggestion feature in VS Code?

Currently, I have made the switch from AngularJS to Angular 6. However, despite this change, VS Code continues to offer me AngularJS code suggestions. https://i.stack.imgur.com/XerhF.png The syntax presented in the first suggestion is for AngularJS while ...

In TypeScript, there is a chance that the object may be undefined, so I make use of an if

I'm encountering an issue with this code snippet. I have a check in place to ensure that the value of 'startups[i].logo' is not undefined, however I am still receiving an error stating that it may be undefined. Can anyone provide insight as ...

A versatile generic type infused with dynamic typing and optional parameter flexibility

Looking to develop a function that can accept an optional errorCallback parameter. In cases where the consumer of this function does not provide a callback, I aim to default to a preset handler. The key criteria here are strong typing and utilizing the ret ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...

Error encountered with the PrimeNG Angular2 Accordion component

I am currently utilizing the PrimeNG accordion module. After importing all components successfully, I encountered an issue with a newly created component. Despite verifying that all modules were imported correctly, I continue to receive the error message ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Is TypeScript failing to enforce generic constraints?

There is an interface defined as: export default interface Cacheable { } and then another one that extends it: import Cacheable from "./cacheable.js"; export default interface Coin extends Cacheable{ id: string; // bitcoin symbol: stri ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Issue with Angular Material Auto Complete not selecting items when filtered

Encountered a problem with the mat-autocomplete control in Angular Material where it fails to include the CSS class "mdc-list-item--selected" on the mat-option and also does not add the mat-pseudo-checkbox to a selected option when the contents are display ...

What are some ways to prevent unnecessary HTML re-rendering when using this.sanitizer.bypassSecurityTrustHtml(value)?

What is the best way to prevent constant HTML re-rendering when utilizing (this.sanitizer.bypassSecurityTrustHtml(value)) in Angular versions 5 and above? ...

Access your account using Google authentication within an Angular framework

My latest project involves creating an API that allows users to log in with Google by using the endpoint http://localhost:3001/api/v1/user/google. Here's how it works: A user clicks on the link http://localhost:3001/api/v1/user/google The endpoint h ...

Implementing a NextJS client component within a webpage

I am currently working with NextJS version 14 and I am in the process of creating a landing page. In one of the sections, I need to utilize the useState hook. I have specified my component as "use-client" but I am still encountering an error stating that " ...

Tips on downloading a dynamically created XML file using ServiceStack and Angular

Although the code below is theoretically functional, it lacks proper error handling. The issue arises when the XML file starts downloading upon opening a new window with the URL generated by the service stack. In case of a server-side error, you are left o ...

Navigate directly to the dashboard page in Angular 5 using RxJS without needing to load the main page first

Utilizing Firebase as the API in my application for authentication, database management, and storage. Implemented a main page (localhost:4200) that loads when the user is not logged in, and a dashboard (localhost:4200/dashboard) for authenticated users. ...

Troubleshooting Angular 4's ng-selected functionality

I'm currently facing an issue with getting ng-selected to function properly. Initially, I attempted to simply add selected in the option tag, but later discovered that I should be using ng-select. Despite trying variations such as ng-selected="true" a ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

The NullInjector has issued an error regarding the lack of a provider for the Decimal

I recently integrated lazy loading into my application. However, one of my services is in need of the DecimalPipe. The structure of my modules goes like this: service -> shared module -> App module To give you more context, I have already added "CommonMo ...