The NgIf-Else statement is functioning incorrectly

As a novice in Angular 8, I am facing some challenges with a section of my code. Specifically, I am attempting to utilize the ngIf Else condition within a div to display a button based on the retrieved value.

<div class="form-group">  
    <div class="row">        
        <div class="input-group col-12 md-12">
            <div class="input-group-prepend">
                <label for="situation" class="input-group-text">Current Situation</label>
            </div>
            <select class="custom-select" id="situation" formControlName="situation" name="situation" [(ngModel)]="employed">
                <option value="employed" name="employed">Employed(including unpaid family workers and apprentices)</option>
                <option value="employed" name="employed">Employed but is temporarily absent(leave without pay, parental leave etc.)</option>
                <option value="unemployed"> Unemployed, looking for work(job seekers)</option>
                <option value="retired"> Retired </ option >
                <option value="unable">Unable to work(disability)</option>
                <option value="domesticWorker"> Woman or man working in their own household(domestic worker)</option>
                <option value="student"> Pupil or Student</option>
                <option value="preschool"> Pre - school child</option>
                <option value="other"> Other(specify) </ option >
            </select>
        </div>
    </div>
</div>

<ng-container *ngIf="employed; then trueCondition else elseTemplate" >
    <div class="btn-toolbar">
        <button class="btn btn-primary" data-toggle="modal" data-target="#householdsFormModal2" data-dismiss="modal" type="button">NEXT</button>
    </div>
</ng-container>
<ng-template #elseTemplate>
    <div class="btn-toolbar">
        <button class="btn btn-primary" data-toggle="modal"
                data-dismiss="modal" type="button"
                [disabled]="householderForm.invalid">SUBMIT</button> 
    </div>
</ng-template>

Even when selecting other options, my button remains in the "Next" state instead of changing to "Submit." Can anyone assist me with this issue?

Answer №1

Utilizing the syntax of ngIfThen necessitates trueCondition to also function as a template.

To learn more, refer to the Angular NgIf documentation.

<ng-container *ngIf="employed == 'employed'; then trueCondition else elseTemplate"></ng-container>
<ng-template #trueCondition>
    <!-- Content displayed if condition is true -->
</ng-template>
<ng-template #elseTemplate>
    <!-- Content displayed if condition is false -->
</ng-template>

Perhaps what you intended to use was the ngIf syntax, represented as

*ngIf="employed == 'employed'; else elseTemplate
.

<ng-container *ngIf="employed == 'employed'; else elseTemplate">
    <!-- Content displayed if condition is true -->
</ng-container>
<ng-template #elseTemplate>
    <!-- Content displayed if condition is false -->
</ng-template>

Furthermore, ensure not to mix up your ngModel named employed with its value, which may be a string set as employed.

The ngModel named employed will always hold a "truthy" value, hence validate using employed == 'employed'.

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

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

Jasmine attempting to access a nonexistent property

I created a very basic component: import { Component } from '@angular/core'; @Component({ selector: 'loading', templateUrl: './loading.component.html', styleUrls: ['./loading.component.scss'] }) export ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

What is the best way to encapsulate a child's properties within a function?

Is there a way to automate wrapping each child of an object with a function? // current code import authController from "./authController"; import appController from "./appController"; import userController from "./userController&q ...

Ensuring Mongoose Schema complies with an external API

My database schema includes a mongoose User schema with the following structure: const User: Schema = new Schema({ // some other fields email: {type: String, unique: true, require: true, validate: [myValidator, 'invalid email provided'], // some ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

The latest release of Angular2, rc1, eliminates all parameters that are not in

In the previous beta version, I was able to analyze using split Location.path(), but now it seems to have been removed. How can I prevent this removal? Interestingly, everything works well with matrix parameters (;id=123;token=asd). This was tested on a ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

CodeBlast: A Kid's Game

I'm facing an issue with a puzzle called "A child's play" on Codingame. My coding language is typescript! The task is as follows: Recently, playful programming has become popular in elementary schools where students use assembly blocks to prog ...

"Exploring the array functionality of Angular's Reactive Forms

I am encountering an issue when trying to access the products array that is located within opticanOrders inside the orderForm. Despite seeing in the console that I should reference the products array like this: orderForm.controls.opticianOrders.controls.p ...

Simulate a new Date object in Deno for testing purposes

Has anyone successfully implemented something similar to jest.spyOn(global, 'Date').mockImplementation(() => now); in Deno? I've searched through the Deno documentation for mock functionality available at this link, as well as explored t ...

Puppeteer: Simulating WebSocket Connections

How can I simulate WebSocket communication in Puppeteer? I'm currently testing my web application without a real backend and have been able to mock Ajax calls using the on request handler. However, I now need to test how my application responds to Web ...

Encountering a problem with Webpack SASS build where all files compile successfully, only to be followed by a JavaScript

Being a newcomer to webpack, I am currently using it to package an Angular 2 web application. However, I am encountering errors related to SASS compilation and the ExtractTextPlugin while working on my project. Here is a snippet from my webpack configurat ...

A guide on implementing the useEffect hook with forwardRef in TypeScript

Here is a piece of code I am working on: import React from 'react'; type shapeTable = { data: string[][]; onMount?: (tableWidth: string) => void; }; type Ref = HTMLTableElement; const Table = React.forwardRef<Ref, shapeTable>(( ...

What methods can be used to prompt TypeScript to analyze varied typing scenarios individually instead of combining them?

Looking at the following code: enum ActionName { BUMP = "BUMP", CLAP = "CLAP", INSPECT = "INSPECT", RUN = "RUN", TALK = "TALK", WALK = "WALK", WAVE = "WAVE", } export enum ...

The function 'sendEmailVerification' is not a property of the type 'Promise<User>'

Hey there, I've been working on my ionic4 app and have encountered an issue with the sendEmailVerification function. The console is suggesting that I may have forgotten to use 'await'. Any ideas on how to resolve this? Thank you. import { In ...

Creating customized infrastructure deployment utilizing AWS CDK for generic use cases

Starting to set up CDK from scratch and seeking advice and best practices from real experiences. I have a variety of apps that will include both my CDK code and the app code in one repository (taking advantage of using similar languages for both app and in ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Retrieving a single item from Firebase database using Angular 5

I have multiple projects to manage: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { this.file = file; ...