Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this issue? (In the image provided, ISRawMaterialInspection and ISRawMaterialRiskState are the empty ones.)

Below is the HTML code snippet:

<input matInput class="mt-20" formControlName="IsOxidizable" *ngIf="form.get('IsOxidizable').value"/>

    <input matInput class="mt-20" formControlName="ISRawMaterialInspection" *ngIf="!!form.get('ISRawMaterialInspection').value"/>
                        
    <input matInput class="mt-20" formControlName="ISRawMaterialRiskState" *ngIf="form.get('ISRawMaterialRiskState').value"/>

And here is the TypeScript code block:

        IsOxidizable: new FormControl({
            value: this.data.IsOxidizable,
            disabled: true,
        }),
       
        ISRawMaterialRiskState: new FormControl({
            value: this.data.ISRawMaterialRiskState,
            disabled: true,
        }),
        ISRawMaterialInspection: new FormControl({
            value: this.data.ISRawMaterialInspection,
            disabled: true

https://i.stack.imgur.com/PDC4C.png

Answer №1

Following some insightful feedback from Eliseo, I made some revisions to my previous response.

As Eliseo mentioned:

The 'if(a)' condition in TypeScript is considered false if 'a' is equal to undefined, null, an empty string(""), 0, or false.

    <input matInput class="mt-20" formControlName="IsOxidizable" *ngIf="form.get('IsOxidizable').value && form.get('IsOxidizable').value !== ''"/>

    <input matInput class="mt-20" formControlName="ISRawMaterialInspection" *ngIf="form.get('ISRawMaterialInspection').value form.get('IsOxidizable').value !== ''"/>
                        
    <input matInput class="mt-20" formControlName="ISRawMaterialRiskState" *ngIf="form.get('ISRawMaterialRiskState').value form.get('IsOxidizable').value !== ''"/>

However, it's worth noting that the original poster (OP) has already accepted the answer and likely resolved the issue, which adds a new perspective.

var a = new String('');

if (a) -> will evaluate to true

This suggests that the OP may have used String objects instead of primitive strings.

The 'if(a)' condition in TypeScript is only false for primitive data types when 'a' equals undefined, null, an empty string(""), 0, or false.

if (new Boolean(false)) -> evaluates to true
if (new String('')) -> evaluates to true
if (new Number(0)) -> evaluates to true

In conclusion, I appreciate Eliseo's clarification, as it has contributed to my improved understanding.

Answer №2

Modifying the HTML code and utilizing

 <input matInput class="mt-20" formControlName="IsOxidizable" *ngIf="form.get('IsOxidizable').value && form.get('IsOxidizable').value !== ''"/>

made a difference. Subsequently, I also updated the main TypeScript file without including

form.get('IsOxidizable').value !== ''
in the HTML snippet. Given that it consistently displayed its title, I made adjustments to the main TS as shown below:

ngAfterViewInit() {
        setTimeout(() => {
            if (this.rawMaterialInformation) {
                this.rawMaterialInformation.IsOxidizable = this.rawMaterialInformation.IsOxidizable?
                    "Oksitlenme :" + this.rawMaterialInformation.IsOxidizable:'';

                this.rawMaterialInformation.MeltingTemperature = this.rawMaterialInformation.MeltingTemperature?
                    "Eritilme Sıcaklığı : " +
                    this.rawMaterialInformation.MeltingTemperature:'';

}

Both modifications proved effective.

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

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

Can we modify the cell width in knitr and pandoc?

When generating an HTML file using knitr/pandoc to display multiple tables in a loop, how can you ensure that each table has the same total width despite having varying numbers of cells? --- output: html_document: theme: cosmo --- {r results ="asis", e ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Verifying the visibility of a div and triggering its closure upon clicking outside of it

Would anyone be able to provide guidance on how I can merge these two scripts into one? Thank you in advance! $(document).ready(function(){ if ($('.myContainer').is(':visible')) { alert('Hello'); } }); $(doc ...

Learn how to safely handle JSON vulnerabilities in Angular by removing the prefix ")]}'," from the JSON data

Our Webservice JSON output is designed to enhance security by starting with the prefix ")]}'," I have read several articles and learned that HttpClient offers libraries to remove this JSON prefix, but I'm struggling to find a proper example. I ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

Arrange the header and input within a div using flexbox to achieve different alignments

I need help aligning the header section vertically and ensuring responsiveness. Using margin-top isn't fully responsive, so I want to align the header at the beginning of the input field. { margin: 0px; padding: 0px; color: white; } #h ...

Maximizing the efficiency of enums in a React TypeScript application

In my React application, I have a boolean called 'isValid' set like this: const isValid = response.headers.get('Content-Type')?.includes('application/json'); To enhance it, I would like to introduce some enums: export enum Re ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

What is the process for sending a post request in Ionic 2 to a Node server running on localhost?

When working with Ionic, I utilized a service provider to access HTTP resources. The Service.ts file looks something like this. Here, data is represented as a JSON object. import { Injectable } from '@angular/core'; import { Http, Headers } fro ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Deduct a digit from a variable

My goal is to decrease the value of revlength each time the loop runs. For example, if there are 2 posts by 'A Google user', then subtract 2 from revlength. This is my attempted solution: var revlength = place.reviews.length; if (place.reviews[ ...

Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribut ...

Troubleshooting my Xpath query for HTML - where did I make a mistake?

Within the <BODY> tags, there is a piece of HTML that I'm attempting to target using scrapy: <section class="content"> <div class="social clearfix"> <div class="profile profile-nano pull-left"> <a hr ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Is the disable feature for React buttons not functioning properly when incorporating Tailwind CSS?

import React, { useState } from "react"; import facebook from "../UI/icons/facebook.png"; import Button from "../UI/Button/Button"; import Card from "../UI/Card/Card"; import twitter f ...

Concealing elements in Angular 2

My intention was to conceal the components, so that when he came back later everything would be just as it was before. The only issue is that I am unsure of how to achieve this. Does anyone have any examples or know of a similar method that could help me ...

Using Angular, I am passing a controller variable as a parameter to a custom filter in the HTML `ng-repeat`. This parameter will be populated within a function so that

At the moment, my setup includes a controller, a filter file, and some HTML. Currently, I am using ng-repeat in the HTML with custom filters that I have created based on the filter being used. For example: ng-repeat="p in persons = (person | toArray | fil ...

The symbol '★' represents the '★' content in CSS

Here is the CSS code I am using: .rating:not(:checked) > label:before { content: '★'; } However, when it is displayed on the screen, instead of seeing a ★, I see â˜. It's strange because if I use Firebug and manually change the ...

Is it best to stick with a static page size, or

While I typically design my webpages dynamically by determining the screen size and creating divs accordingly, I'm curious about the advantages of using a 'static' sizing approach (such as using pixels). Any insights on this contrasting meth ...