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

What is the best way to navigate my Page while my Dialog Component is displayed?

Is there a way to enable scrolling on the background when a dialog component opens up? By default, scrolling is disabled when the dialog appears. How can we allow scrolling in the background? Here is the code snippet: import React, { useState } from &apos ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Dependency in NPM that imports/includes from the main directory of the application

Imagine creating an application named App, which includes an npm dependency called package. The package requires that the App adheres to a specific file structure: App/ node_modules/ package/ index.js package.json folder/ file.js index.js pac ...

How can one retrieve videos from a YouTube channel using Angular 2 within the Ionic 2 Framework?

Can someone help me understand how to fetch and display videos in my Angular 2 Android App using Ionic 2? I am new to both technologies. .component.js File export class HomePage implements OnInit { private videoListArr = []; private title = []; privat ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Perform time update every second

Is it feasible to have my timeupdate function run every second? (Using VUE CLI) @timeupdate="videoSecond" videoSecond(){ let Second = this.player.currentTime(); let CaptureList = this.capturesList; CaptureList.forEach(element => ...

Loading a specific number of rows in Datatables upon page loading: How to do it?

Recently, I came across a code snippet that uses AJAX to retrieve data from a specific URL and then displays the information in a table. However, I have a requirement to only load and display the first 10 rows of data during the initial page load process. ...

Unexplained quirks observed in AngularJS $watch during the initialization of a controller

I am working with a code snippet that utilizes AngularJS: var app = angular.module('Demo', []); app.controller('DemoCtrl', function ($scope) { function notify(newValue, oldValue) { console.log('%s => %s', oldValue, ...

How can I adjust my settings so that my image resizes from the center rather than the top left corner?

I'm having an issue with my code for resizing images on rollover - the image is currently resizing from the top left corner instead of from the center. How can I adjust it to resize from the center of the image? <script> $('i ...

Issue with SVG animation causing unnecessary duplication of circle shapes when utilizing animateMotion

I have implemented animateMotion to create an animation along a path. Below is the code snippet that demonstrates this: <!DOCTYPE html> <html> <head> <title>Example Of Many Things!</title> </head> <body> ...

The scope of the inferred type parameter in the generic TypeScript function is overly broad

I'm currently working on creating a function that takes in another function (a React component) as an argument and then returns a related function. My goal is to define specific requirements for the input function, ensuring that it accepts certain pr ...

Tips for creating a vertical drawer using jQuery and CSS

Hello, I am currently working on developing a drawer component using Ember.js. If you want to view the progress so far, feel free to check out this jsbin http://jsbin.com/wulija/8/edit My goal is to have the drawer look like the following initially: +--- ...

Building a bespoke pagination feature with react-table

Looking to personalize the pagination with links for "Previous," page numbers, and "Next" like this example: I'm currently using react-table version 7 but have been unable to replicate the desired pagination style. I need it to be dynamic based on th ...

Dealing with Request Disconnection in a Node.js and Express Application

I have a node/express application and I am looking for a way to detect unexpected interruptions in the connection. I have attempted using the following code: req.on('close', function () { //this handles browser/tab closure scenarios }) Howev ...

Why isn't the image adjusting its size to fit the container it's placed in? Am I missing something?

My issue involves getting an image to resize and stay within its designated div. However, the image continues to spill over onto the div below when I adjust the browser size or view it on my laptop. I have not set any fixed dimensions for the image. I am ...

Notification of Exceeding File Size Limit

Seeking assistance with implementing a 'filesize' error message into a script used for uploading BLOB files to a mySQL server. if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($dat ...

What are the Typescript object types where the keys are functions that take a single generic argument consistently?

Explaining this concept in English is quite challenging, but here's what I'm aiming for: const operations = { store: (input: T): T => { return input; }, discard: (input: T): void => { console.log(input); } } In both fun ...

Creating dynamic divs on button click for my project is something that I must do, and I will

When the user clicks on the Add button, a new div should be added as shown in the image above. Implementing this functionality using Bootstrap is crucial because the divs must rearrange correctly based on different resolutions such as 1920x900, 1280x600, ...

Tips for effectively using ngOnChanges in Angular 2 to validate inputs without causing the 'Expression has changed after it was checked' error

I attempted to create my own custom component with basic validation using regex that can be passed as input to the component. There are two scenarios to consider: one where the form is initially empty (new item form) and another where data is already prese ...