Identifying when ngModel is dirty

In my application, the input fields are populated dynamically based on the API response. Each field has a corresponding set of buttons associated with it, which I only want to show when the field is edited.

Here is an image of the form:

https://i.sstatic.net/8opQq.png

I am currently using simple ngModel for viewing and changing the values. Since the fields do not have complex validations, I am not interested in using a reactive form approach. My requirement is that when a user types into a field, the respective button set should appear. Upon clicking either button, the field should return to its original pristine state.

Below is the code snippet for populating the template:

<h5 class="mb-4">Report Configuration</h5>
<div class="form-group row" *ngFor="let config of reportConfig">
  <label class="col-sm-12 col-md-4 col-form-label">{{config.title}} <span
      class="text-danger">*</span></label>
  <div class="col-sm-12 col-md-6 col-lg-6">
    <input type="text" [class.is-invalid]="false" [id]="config.propertyKey" [(ngModel)]="config.propertyValue" class="form-control" />
    <!-- On typing the field should be marked dirty & buttons should appear -->
  </div>
  <div class="col-sm-12 col-md-2 col-lg-2 pl-0">
    <mat-icon class="mr-2" (click)="should mark the field pristine">check_small</mat-icon>
    <mat-icon color="warn" (click)="should mark the field pristine">close_small</mat-icon>
  </div>
</div>

Can this functionality be achieved using ngModel, or do I need to use FormArray to accomplish this?

Answer №1

An ngModel is inherited from AbstractControlDirective, allowing you to access its properties such as valid, touched, or dirty. To do this, use a template reference variable (named ""#nameID" in the code below).

<div *ngFor="let config of reportConfig">
    <input name="name" #nameID="ngModel" [(ngModel)]="config .name"/> 
    <button *ngIf="nameID.dirty">undo</button>

    <pre>
    {{nameID.control.dirty}} or {{nameID.dirty}}
    {{nameID.control.touched}} or {{nameID.touched}}
    {{nameID.control.valid}} or {{nameID.valid}}
    </pre>
</div>

Remember that a template reference variable has its own "scope" within an ngFor loop, so there should be no issues with using it.

Answer №2

Here is a tip for your ngModel in HTML:

(change)="detectDirty(value)"

Remember to add this code to your TypeScript file as well:

detectDirty(value) {
 if (value.dirty) {
  //Your code goes here
 }
}

In essence, the ngModel utilizes the dirty property to determine if an input has been modified or not.

Answer №3

If you want to assign a template reference variable, use the # symbol:

<input #variable="ngModel" type="text" [class.is-invalid]="false" [id]="config.propertyKey" [(ngModel)]="config.propertyValue" class="form-control" />

Once set, you can modify the pristine property by calling the markAsPristine() function:

<mat-icon class="mr-2" (click)="variable.control.markAsPristine()">check_small</mat-icon>

For more information, refer to this example in the official documentation: https://angular.io/guide/forms#show-and-hide-validation-error-messages

Remember: Reactive forms not only handle form validation but also provide access to form values, unlike template-driven forms.

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

Unpacking objects in Typescript

I am facing an issue with the following code. I'm not sure what is causing the error or how to fix it. The specific error message is: Type 'CookieSessionObject | null | undefined' is not assignable to type '{ token: string; refreshToken ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model. Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but console.log(todoItem.get('descrip ...

Utilizing Vue.js for Tabs in Laravel 5.8

I am encountering an issue in Laravel while attempting to set up a Vue instance for tabs. Currently, only Tab 1 and Tab 2 are displayed without any content, and the tabs themselves are not clickable links. Could this problem be related to how I am calling ...

The inability to access data from an API is a result of the lack of a functioning

I'm encountering an issue with fetching data from an API. When I try to map through my array of data, I receive an error message stating that 'map is not a function'. I fetched the data on the index page and passed it as props to the CoinLis ...

Eslint has encountered a parsing error, it was not expecting that token

I encountered the issue Error: Unexpected token .. raised by eslint while working with this code snippet. Can anyone spot what's causing it? const Public = ({ loggingIn, authenticated, component, ...rest }) => ( <Route {...rest} render={(pr ...

The property is accessed prior to being initialized

In my code, I have a class defined as follows : export class Group { id: string; name: string = ''; type: 'local' | 'ldap' = 'local'; members: number[] = []; This class is being used in my applicatio ...

What is the most efficient way to extract distinct elements from an array in NodeJS?

I am in the process of developing a script that generates random loadouts for Mordhau. Currently, I am not focusing on calculating point values, but I would like to ensure that no perks are repeated in the selection process. All the perks are stored in a ...

Node API session functioning properly on Postman but experiencing issues in web browser

I am currently working on developing a node API for authentication purposes. The login session is created and stored successfully when tested in Postman. However, I am encountering an issue where it does not work in the browser. I suspect that the problem ...

Using a responsive menu (mmenu) can lead to an increase in Cumulative Layout

I've implemented mmenu as a responsive menu on my website. Recently, I discovered errors in Google's search console related to high CLS (Cumulative Layout Shift). Upon further investigation, I noticed that when loading my page in "slow" mode for ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

Rerendering of a React component occurs upon a change in its state

Previously, my form was functioning flawlessly. However, after making a few modifications to the state variables, the input field now loses focus upon a state change. I am utilizing MUI and everything was working perfectly until this sudden issue arose f ...

Effectiveness in identifying groups (?: => task(?:s+)?team COMPARED TO effort(s+)?group

Both of these formats suit my needs: E1=> work(?:\s+)?group E2=> work(\s+)?group I am looking to match either workgroup or work group, taking into account that the space could also be a line break (\s+)? My main concern is with th ...

Animating scrollTop using jQuery is a useful feature for creating

I am facing an issue with several section tags within a div that has overflow set to hidden. The structure of the code is as follows: <div id="viewport"> <section> content </section> <section> content </ ...

Production Server experiencing issues with sending Large Lists via Http Post

I'm experiencing an issue where the server is unable to read values from a large list when sent using Post. Oddly enough, this works on the homologation server but not on the production server. Http post AngularJs $http({ url: $rootScope.raiz_ws ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

Having trouble installing Bootstrap using the `npm i bootstrap` command? It seems like the

The npm i bootstrap command is not working when trying to install Bootstrap. Nothing is being added to the packages.json file or node_modules directory. Here are the dependencies listed in the package.json file: "dependencies": { "@angu ...

What could be the reason for the empty response in my PATCH request in Javascript?

I am facing an issue with my app that runs Rails in the backend and Javascript in the frontend. The controllers, routes, and CORS are all set up correctly. Both my Post and Get requests work without any problems. However, when I attempt to make a patch req ...