Developing forms in Angular 5 involves the decision of either constructing a specific model for the form group inputs or opting for a more generic variable with two

As a newcomer to Angular, I've noticed that most courses and tutorials recommend using a model or interface for form data. However, I have found it more efficient and straightforward to just use a generic variable with two-way data binding.

Could someone please clarify the importance of defining a model for form data?

Instead of utilizing:

  attorney: any = {
  };

Many tutorials suggest:

attorney: Attorney = {...}
//where Attorney is a class with various parameters

Feel free to check out my code implementation below.

https://stackblitz.com/edit/angular-xkcgng?file=app%2Fapp.component.html

Answer №1

While it is possible to use any for any variable, field, or parameter in TypeScript, doing so poses a risk as it removes the safety provided by the compiler.

interface Lawyer {
    name: string
}
class Company {
    lawyer: Lawyer = {
        Name: 'Test' // results in a compile time error, which is desirable
    }
}

By using any, you open up the ability to access any field on an object, potentially leading to errors.

lawyer: any= {
    Name: 'Test' // results in a compile time error, demonstrating its benefit
    age: 10
}
console.log(this.name + ' '+this.age.trim('0')) // instead of catching this error at compile time, it will result in a runtime error

Answer №2

There is no strict rule on how to approach this issue. Whether you opt for a custom type or stick with using 'any', the decision is up to you.

It's important to consider the advantages and disadvantages of each method. @Titan presents a strong case for utilizing a custom type, as it allows the compiler to handle the heavy lifting for you.

The key is to choose the approach that aligns best with your preferences. If there's no compelling reason not to use 'any' in your situation and it simplifies your workflow, then go ahead and use 'any'. However, when 'any' becomes unsuitable and a custom type would be more effective, feel free to make the switch.

You could also experiment with both options to determine which one better suits the specific feature you're developing.


That said, in your StackBlitz demonstration, you seem to be combining template-driven forms with reactive forms. If you're employing the 'FormBuilder', avoid using 'ngModel' to connect to your properties within the same form object values. Instead, utilize 'formControlName' or similar methods. When dealing with plain objects, 'ngModel' may be necessary as it provides the binding needed.

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

An error has occurred in Node.js/Express.js: The path argument is missing and is required for res.sendFile

I have successfully uploaded my files using Multer to a specific directory. However, I am now facing an issue while trying to download the same files that are displayed in an HTML table with individual download options. Below is the code snippet: Node.j ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...

An issue arose while compiling the template for 'AppRoutingModule', indicating that function expressions are not compatible with decorators

Currently, I have implemented the "CaseInsensitiveMatcher" based on the solution suggested by Alireza. However, I am facing an issue when attempting to create a production build as indicated by the following error message: "'urlMatch' referenc ...

Is there stability in using *ngFor for lists in Nativescript Angular?

Update: I have inquired about the current status of RadListView in Nativescript, questioning if it still exists. You can find more information here. Initial query: Is it suitable to utilize *ngFor for lists in Nativescript? Typically, I see recommendatio ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

Ways to utilize Subjects for sharing global information in Angular 6

I have been struggling to find an effective way to share data between two components that have the same parent in an Angular application. Currently, I am working with an Angular Material stepper where Step 1 contains one component and Step 2 contains anot ...

Svelte language switcher experiencing technical difficulties

Currently delving into Svelte 3, I embarked on a project intended to be shared on GitHub in English. However, I realized that some of my friends do not speak English. To accommodate different language preferences, I decided to create a language switcher. H ...

Modify animation trigger when mouse hovers over

I am looking to create a feature where a slide overlay appears from the bottom of a thumbnail when the user hovers over it, and retracts when the user is not hovering. animations: [ trigger('overlaySlide', [ state(&ap ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

Attempting to combine numerous observables into a single entity within an Angular 2 project

I am grappling with the concept of Observables in RxJs. My task involves displaying all users for a specific site on a page. The User and SiteUser entities are located in separate API endpoints. Here are the relevant endpoints: userService.getSiteUsers(si ...

Angular2 ngFor, encountering undefined property

Having an issue where one of my properties is showing as "undefined" even though it is defined. Can't seem to find a solution: I have a parent component with the following data: @Component({ selector: "app-my-products", templateUrl: ...

Utilizing variables to set the templateUrl in Angular2

Trying to assign a variable to the templateUrl in my component, but it's not functioning as expected. @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.comp ...

Incorporating Sass into a TypeScript-enabled Create React App

Having recently transferred a create-react-app to typescript, I've encountered an issue where my scss files are not being recognized in the .tsx components. The way I'm importing them is as follows: import './styles/scss/style.scss'; ...

What is causing this error to appear during the npm install process in my Angular project?

I encountered an issue in my Angular 7 project recently. When running npm install, the following error occurred: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

What steps are required to customize a pre-existing DevExtreme JQuery DataGrid that was initially built in a cshtml file using Typescript?

I'm currently developing a web application using DevExtreme JQuery. Within the frontend, I have set up a DataGrid in a cshtml file. With DevExtreme functionality, it's possible to include an Add Button to the DataGrid that triggers a popup for in ...

Issue encountered while developing custom Vuejs + Typescript plugin

In my index.ts and service plugin files, I have this structure: https://i.sstatic.net/Oh3Gq.png service.ts declare interface Params { title: string; description?: string; type?: string; duration?: number; } export default class ServiceToast { ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

Encountering difficulties installing npm bootstrap@3 within the Angular framework

Recently, I started learning Angular and decided to integrate Bootstrap into my Angular project. However, when I entered npm install --save bootstrap@3 into the terminal, the following warning messages were displayed: C:\Users\ssc\Angular-T ...