When using Angular 2, I encountered an issue where the ngIf directive was not functioning properly when attempting to implement two-way

I'm currently working with Angular2 and utilizing the two-way binding concept [(ngModel)]. I have a form on my page that requires validation of the pristine state of an element. To achieve this, I've implemented ngIf to check the pristine state of the element. However, I'm facing an issue where the condition is not being met consistently. I need to validate the pristine state every time the model changes. Below is a snippet from my app.component.html:

 <form (ngSubmit)="angular2form(myAngular2Form.employeeDob)" [ngFormModel]="myAngular2Form">

 <input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />            
  <div *ngIf="employeeDob.pristine">
    <p>Please enter the date</p>
 </div>
 <button type="submit" class="btn btn-primary">Register</button>

</form>

Here is a snippet from my component:

 export class AppComponent {

employeeDob: String;

  constructor(private myform: FormBuilder) {
    this.employeeDob = '';
 }
 angular2form(date) {
     alert("date submitted successfully");
 }
 }

Any suggestions would be greatly appreciated.

Answer №1

<input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" #date="ngModel" required  /><br>
  <div [hidden]="date.valid || date.pristine">
    <p>Please make sure to enter the date</p>
 </div>

fresh from the source

https://angular.io/docs/ts/latest/guide/forms.html

Answer №2

Prisitine applies to the Control, not the value.

You can use:

<input #employeeDobCtrl="ngForm" type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />        
<div *ngIf="employeeDobCtrl.pristine">    

(for the previous forms module)

Answer №3

pristine is a condition that indicates whether the user has not yet interacted with the form. Perhaps you should consider checking for the state of dirty instead? Another option is to utilize the hidden tag and substitute

<div *ngIf="employeeDob.pristine">

with:

<div [hidden]="employeeDob.pristine">

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

Troubleshooting: AngularJS Form Submission Failure

As a novice in Angular and not a JavaScript expert, I am facing challenges with form submission. My task involves loading movie showtimes from an http API and using ng-repeat to display them within a page container. The REST API requires a zipcode input, w ...

Toggle the visibility of textboxes depending on the input value in textbox using AngularJS

On my page, there is a text box and two buttons. The text box is populated with data from the database. If the text box has a value, I want to display Turn Off and hide the other button. If the text box is empty, I want to show Turn On and hide the other b ...

Viewing Image in Modal on Click

Despite numerous attempts, I have been unable to make this work, even after trying various examples. The issue at hand is with a list of imageURL's that are displayed on the webpage. The goal is to allow users to click on an image, which would then o ...

Develop a unique directive that embeds HTML content in a different location than where it is initially utilized

After creating an AngularJS directive, the task at hand is to insert an HTML element as a child of the body element. The challenge arises when this element needs to contain another custom component, which is defined as a directive. My initial attempt invo ...

Using the pipe, filtering will not be activated by clicking

In order to find the perfect products, I need to utilize the myfilters filter. Unfortunately, this is not currently working as expected. Here is a snippet of the store's HTML: <h2>store</h2> <select> <option *ngFor="let g of G ...

Make sure to include all enum type values within the function's body to ensure comprehensive coverage

I am defining an enumeration called ApiFunctions with values like "HIDE", "SET_READ_ONLY", and "DESCRIPTION". Also, I have a type ValueOfApiFunction that should include all values of ApiFunctions. Additionally, I have a logic that listens for messages on ...

The 'npm update' command seems to be failing when attempting to update dependencies within Angular2

I am looking to upgrade the outdated dependencies in my Angular 2 project. Upon running npm outdated, I identified several dependencies that need updating. However, when I attempt to update them using the npm update command, it does not seem to work as exp ...

In the given situation, which would be the preferable option - making use of useEffect or opting for

My custom hook fetches data from a smart contract as shown below: export const usePoolLength = () => { const [length, setLength] = useState(0); const _getPoolLength = useCallback(async () => { const poolLength = await getPoolLength() ...

Having trouble getting TypeScript to install using npm on a Mac?

My goal is to use Typescript as a local dependency by checking it into my devDependencies and using it via an npm script after installing it with 'npm install'. However, when I try this on my machine, I find that Typescript (and webpack-cli as w ...

"Experience the power of Angular with 15 incredibly dynamic components utilizing the compileModuleAndAllComponentsAsync function

Currently, I am in the process of transitioning a project from Angular 8 to version 15. One of the key features of the application is dynamic product cards, where the template for these cards is arbitrary HTML loaded from the server and unknown during deve ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...

Firefox is having trouble keeping <select> tags within their designated borders

I am currently developing a mobile app that requires the use of 3 <select> elements stacked on top of each other. It is crucial for these tags to align perfectly with each other and not extend beyond the boundaries of the background div. I have manag ...

Verifying the name's uniqueness and disregarding it in case of any alterations

I am currently working on a form that includes a modal to allow users to modify their name and email address. The issue I am facing is that the form sends a request to the server to check for unique values in all cases. While this is appropriate when creat ...

Transform JSON into a TypeScript interface with a specialized Date method

Within my Angular 7 project, there is a Post Model defined as follows: export interface PostModel { id: number; created: Date; published: boolean; title: string; } I have implemented an Angular service method aimed at retrieving posts: public g ...

Array - Modifications do not pass down to the child component

I am observing the following structure in the code: <div id="join-container"> <join-chain id="my-join-chain" [selectedColumn]="selectedColumn" (updatedStatements)=onUpdatedStatements($event)> </join-chain> <tile-ca ...

Sorting data in Angular Material Datatable is not functioning as expected

I am facing a problem with my code. The Material Datatable and filter module are working fine, but sorting and pagination are not functioning properly. The data source is coming from my API. The sorting arrows are displayed and clickable, but the table ...

Issue with ARIA attribute not supported or prohibited in Kendo component

I've encountered an accessibility problem with the Kendo Sortable component in my current project. The issue revolves around ARIA attributes, specifically receiving a warning message indicating: When using the Siteimprove tool to run an accessibility ...

Issue: The Clerk authentication function was invoked, but Clerk was unable to detect the usage of clerkMiddleware() (or the outdated authMiddleware())

I've been following a YouTube tutorial (https://youtu.be/zgGhzuBZOQg) to create a next.js project with Clerk. However, I keep encountering error messages in the terminal every time the site loads: Error: Clerk: auth() was called but Clerk can't ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...