The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifice the static type power provided by TypeScript.

I noticed that all observables and the main object are typed as any. Is there a way to prevent this from happening?

Moreover, I learned about TypeScript 2.1 introducing "mapped types" which could potentially be useful in converting a standard interface into an interface of observables without losing the properties' types. Surprisingly, there seems to be very little discussion surrounding this feature in the context of Angular.

Answer №1

Angular forms can be categorized into two types:

  1. Template driven forms

and

  1. Reactive forms (utilizing FormGroup/FormBuilder).

I personally prefer Reactive forms due to the customizable validation option and the ability to create dynamic forms. These features make Reactive forms more powerful.

For more information on reactive forms, you can visit this link about Angular2 reactive form value confirmation

In terms of observables, we often use a type like Observable <person[]>.

We can define an interface for each object and utilize it in the component.

Although mapped Types offer options like readonly and proxies, not many people are discussing them currently since they are available in TypeScript 2.1 while our angular app is using "typescript": "~2.0.10" for stability.

Mapped Types

A common task involves making all properties of an existing type optional. For instance, if we have a `Person`:

interface Person {
    name: string;
    age: number;
    location: string;
}

A partially populated version would look like:

interface PartialPerson {
    name?: string;
    age?: number;
    location?: string;
}

With Mapped types, `PartialPerson` can be created as a generalized transformation of the type `Person`:

type Partial<T> = {
    [P in keyof T]?: T[P];
};

type PartialPerson = Partial<Person>;

Mapped types involve taking a union of literal types and generating new properties for a new object type. They are similar to list comprehensions in Python, but instead of creating new elements, they generate new properties in a type.

In addition to `Partial`, Mapped Types can facilitate various transformations on types:

// Keep types unchanged, but make each property read-only.

    type Readonly<T> = {
        readonly [P in keyof T]: T[P];
    };

// Retain the same property names, but change the value to a promise instead of a concrete one

    type Deferred<T> = {
        [P in keyof T]: Promise<T[P]>;
    };

// Create proxies around properties of T

    type Proxify<T> = {
        [P in keyof T]: { get(): T[P]; set(v: T[P]): void }
    };

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

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

Typescript - The type is lacking certain properties from another type, despite having all options defined

I have defined the following TypeScript declarations: type TDisplayKey = "a" | "b" | "c"; const DISPLAY_KEYS: Record<string, TDisplayKey> = { A: "a", B: "b", C: "c" }; const DISPLAY_KEY_TITLES: Record<TDisplayKey, string> = { [DISPLA ...

Is it possible to create a class object with properties directly from the constructor, without needing to cast a custom constructor signature

class __Constants__ { [key: string]: string; constructor(values: string[]) { values.forEach((key) => { this[key] = key; }); } } const Constants = __Constants__ as { new <T extends readonly string[]>(values: T): { [k in T[num ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

Troubleshooting Angular and ASP.NET Core MVC: Addressing the "Uncaught SyntaxError: Unexpected token '<'" issue with index file references post deployment

My application is built using ASP.NET Core MVC and an Angular UI framework. Everything runs smoothly in the IIS Express Development Environment, but when switching to the IIS Express Production environment or deploying to an IIS host, I encounter issues wi ...

Preview of Azure AD Consent Scopes and Access Token Version Error in Msal Angular

Currently in the process of updating my web application with the new MSAL library, @azure/msal-angular, from previously using the old ADAL library. The frontend of the web app is built with Angular 5 and communicates with a backend ASP.NET Core Web API. ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Using the useRef validation can lead to errors when trying to reference the current value against an input

Currently, the code is functioning well but an error alert from Typescript needs to be addressed. A warning pops up regarding the use of ref.current.value. ERROR 1. TS18048: 'ref.current' is possibly 'undefined'. To tackle this issue, ...

File resolution issue with TypeScript

While I am aware that using TypeScript outFile is generally advised against, I currently have no choice but to utilize it until a more suitable solution like AMD can be implemented. It seems like there may be a "module splitting issue" in my project. In t ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Invoke a shared function within multiple component HTML files when an onchange event is triggered by a universal service

Hello there, I am currently working with angular 11. In my project, I have three components named C1, C2, and C3. These components do not have a parent-child relationship but they all share a common method called F1. Right now, F1 is declared in each compo ...

Using Sass variables within Angular2 components

In my project, I leverage Angular2 and angular-cli. Within the global style.scss file, I have defined several Sass variables. How can I retrieve these variables within my custom components (component.scss)? Should I perhaps import a separate file contain ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Using Webpack 4 and React Router, when trying to navigate to a sub path,

I'm currently working on setting up a router for my page, but I've encountered a problem. import * as React from 'react'; import {Route, Router, Switch, Redirect} from 'react-router-dom'; import { createBrowserHistory } from ...

"Unlocking the treasure trove: Extracting a single item from my Firebase real-time database using

Searching for the user's article in my Realtime database to display information. https://i.sstatic.net/yCdgf.png This is my Ionic script page Below are the imports I have: I am able to retrieve the user's ID, but I'm facing difficulty in ...

Since making the switch from Angular 5 to 6, I've been consistently encountering a frustrating issue: the error message "timers in xml2js cannot

As mentioned in the title, I am constantly encountering a strange error. Despite attempting to uninstall it using npm uninstall xml2js, nothing has proven effective thus far. https://i.stack.imgur.com/DccM7.png ...

What is the best way to retrieve data from a server and display it using Highcharts in Angular 2

This is my chart component and I am trying to display a chart with values from the server. Unfortunately, it's not working even though it works with static values. In the ngOnInit method, I call the web service and store the data in a variable called ...

Angular script error when running 'npm run' on select computers causing Unix command issues for some users but not all

Recently, I've encountered a puzzling issue at my workplace that has been difficult to diagnose. We utilize scripts in npm within the Angular framework to launch a local server instance. Strangely enough, some of my colleagues' computers are thro ...

Ensure that compiler errors are eliminated for object properties that do not exist

Coming from a JavaScript background, I recently began working with Angular 2 and TypeScript. Below is a snippet of my code: export class AddunitsComponent implements OnInit { public centers:any; constructor(){ this.centers = {}; }} In my view, I h ...