I'm having issues with the functionality of my code inside the ng-template and ngIf. What could be

I am facing an issue with my method that is supposed to display the specified HTML content. However, it seems like the ngIf condition within the code block is not functioning correctly. Can someone help me understand why the ngIf statement is being ignored?

        <div class="field">
            <label for="birthday">Birthday</label>
            <mat-form-field class="example-full-width">
                <mat-label>Choose a date</mat-label>
                <input matInput [matDatepicker]="picker" id="birthday" [formControl]="birthdayFormControl" (dateInput)="calculateAge()" (dateChange)="calculateAge()">
                <mat-hint>MM/DD/YYYY</mat-hint>
                <mat-datepicker-toggle matIconSuffix [for]="picker">
                </mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
        </div>
    </div>


<ng-template *ngIf="isApplicantMinor()"> // - this part is not working as expected
<div class="row">
    <div class="column">
        <div class="field">
            <label for="parentBirthday">Birthday</label>
            <mat-form-field class="example-full-width">
                <mat-label>Choose a date</mat-label>
                <input matInput [matDatepicker]="picker" id="parentBirthday">
                <mat-hint>MM/DD/YYYY</mat-hint>
                <mat-datepicker-toggle matIconSuffix [for]="picker">
                    <!--                        <mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>-->
                </mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
        </div>
    </div>
    <div class="column">
        <div class="field">
            <label for="birthday">Parent's Email Address</label>
            <mat-form-field class="example-full-width">
                <mat-label>Email</mat-label>
                <input type="email" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
                      placeholder="Ex. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7c6d784c69746d617c6069226f6361">[email protected]</a>">
                <mat-hint>Enter your parents email!</mat-hint>
                <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
                    Please enter a valid email address
                </mat-error>
                <mat-error *ngIf="emailFormControl.hasError('required')">
                    Email is <strong>required</strong>
                </mat-error>
            </mat-form-field>
        </div>
    </div>
</div>
</ng-template>

In the TypeScript

isApplicantMinor(): boolean {
    this.applicantIsMinor = false;
    if (this.applicantAge < 18) {
        this.applicantIsMinor = true;
    }
    return this.applicantIsMinor;
}

 calculateAge() { // a date on string "22/10/1988
    //debugger;
    this.applicantIsMinor = false;
    var dateString = moment(this.birthdayFormControl.value).format("MM/DD/YYYY") || moment(new Date().toDateString()).format("MM/DD/YYYY");

    let age: number = 0;
    if (dateString === undefined || dateString?.length === 0) {
        dateString = new Date().toDateString();
    }
    var dateParts = dateString.split("/");
    var dateObject = new Date(+dateParts[2], +dateParts[0], +dateParts[1]);
    console.log(dateObject);

    if (dateString) {
        var timeDiff = Math.abs(Date.now() - new Date(dateObject).getTime());
        age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
        console.log(age);
    }
    this.applicantAge = age;
    if (this.applicantAge < 18) {
        this.applicantIsMinor = true;
    }
    return age;
}

Answer №1

To improve performance, consider swapping out ng-template for ng-container. This change is recommended because *ngIf actually relies on ng-template internally. When Angular encounters the structural directive *ngIf, it will restructure the element by moving it into a ng-template and breaking down the *ngIf expression into two distinct directives, [ngIf] and [ngIfElse].

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

What is the technique for obtaining a complete AST representation of a union type in TypeScript?

Although I am familiar with ts-ast-viewer, I am unsure of how they extract a list of elements from the union. I have experimented with different existing solutions, such as this one, but it appears that most of them are outdated. Some ts.[methods] have be ...

Having trouble installing the generator-angular2

While attempting to install generator-angular2, an error message is displayed: npm WARN ENOENT ENOENT: no such file or directory, open '/usr/local/lib/node_modules/generator-angular2/package.json' npm WARN ENOENT ENOENT: no such file or direc ...

Preventing AngularJS from Binding in Rows: A Solution

Currently, I am utilizing AngularJS version 1.5.3 and I am facing an issue with my services. I have two services - one that retrieves Area names and the other that fetches details for each Area. In my code, I first call the service to get the Area names an ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

When using Angular server-side pagination with ngrx and Express in Node.js, I often encounter discrepancies in the indexing across different stacks

After successfully implementing server-side pagination in Angular, I encountered an issue where the page was set to 1 initially, but the mat-paginator component started at index 2. Despite functioning correctly when changing pages, this discrepancy puzzled ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

There seems to be an issue with Firebase authentication on firebase-admin in node.js. Your client is being denied permission to access the URL "system.gserviceaccount.com" from the server

Issue I've been utilizing Firebase auth on my client and using firebase-admin to verify on the server. It was functioning well until I decided to migrate to a different server, which caused it to stop working. The crucial part of the error message i ...

The automatic inference of function argument types and the implementation of conditional types

I'm facing a specific scenario: There's a function that takes in a boolean and returns either a RealItem or an ImaginaryItem. I'm using conditional types to determine the return type based on the boolean argument. type RealItem = { color: s ...

Internet Explorer does not return results when using AJAX during the onchange event (specifically for IE only

My code is functioning correctly on other browsers, however in IE it does not provide any result when I select the dropdown button. Instead, it changes and displays an empty result. This is my AJAX: $("#book").change(function(){ var DOMBULK = $(" ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Provide initial values to a custom TypeScript hook

As a new TypeScript user, I am trying to implement a hook called useForm to use in all forms. However, I am facing an issue with passing initial values using the code snippet below. Can someone help me troubleshoot this? interface IForm1 { name?: strin ...

javascript utilizing underscorejs to categorize and aggregate information

Here is the data I have: var dates = [ {date: "2000-01-01", total: 120}, {date: "2000-10-10", total: 100}, {date: "2010-02-08", total: 100}, {date: "2010-02-09", total: 300} ]; My goal is to group and sum the totals by year like this. ...

Discover the step-by-step process for moving data between collections in MongoDB

I am currently working on nestjs and have two collections, one for orders and the other for payments. My goal is to retrieve a single entry from the orders collection and save that same entry into the payments collection. Below is the code for the service ...

Is it possible for me to include the id attribute in an HTML element that has been generated using React

While working with Selenium to create end-to-end tests for a React-based web application, I noticed that very few HTML elements have the id property set. Since our development team is preoccupied with other tasks, I've taken it upon myself to address ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured. Currently, the regex /(\d+)(?=h ...

Sending information to a service from the main.ts file in an Angular application

Within my Angular CLI application, I have a main.ts file that includes the following export statement. This file serves as a microservice that receives CONTEXT from another microservice. export default { async mount({ rootElement, context }: Extension) ...

Expanding the base class attribute in Typescript

I am currently in the process of developing a wrapper class to enhance the functionality of ReactReduxForm's Control component. Below is the initial class/component setup: export class Control<T> extends React.Component<ControlProps<T> ...

Trouble with displaying image sources in dynamic content with Vue and Vuetify

Currently, I am developing a component that displays tabs along with their corresponding HTML content using v-tab, v-tab-items, and v-tab-item. In the v-tab-item section, I have included the following snippet: <v-card flat> <v-card-text v-html=& ...

Automatically generated list items are failing to react to the active class

I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET requ ...