Using Conditional Checks in Angular 2 for Form Validations

I am looking to create a universal template for both guest and customer registration forms, with varying validations.

Imagine we have a Register form for Guests where firstName is required

<form #f="ngForm" novalidate (ngSubmit)="save()">
                <label>First Name:</label>
                <input type="text" name="firstName" [(ngModel)]="values.FirstName" required #firstName="ngModel">
                <div *ngIf="firstName.hasError('required') && (!firstName.pristine && !f.submitted)" class="text-danger">You must include a first name.</div>
</form>

For Customers, firstName is optional

<form #f="ngForm" novalidate (ngSubmit)="save()">
                    <label>First Name:</label>
                    <input type="text" name="firstName" [(ngModel)]="values.FirstName" #firstName="ngModel">

</form>

I aim to use one single template for both forms while accommodating different validations. How can I accomplish this? Thanks in advance!

NOTE: While I know that using reactive forms could achieve this, I prefer to do it with Template-Driven forms.

Answer №1

After reviewing the discussions on this subject, it is suggested to experiment with

<input name="first" ngModel [required]="isRequired">

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 set up an empty {[key: string]: string} object in TypeScript?

interface a { d: {[key: string]: string} } class a { d = {} } The error message returned is as follows: Subsequent property declarations must have the same type. Property 'd' must be of type '{ [key: string]: string; }', but ...

Ionic 5.9.1 and Angular 12 FormControlName

Currently, I am delving into the realm of Reactive Forms with Angular 12 and Ionic 5.9.1 on my app. To my surprise, upon checking the latest documentation on the https://ionicframework.com/docs/api/input#properties Ionic website, I realized that there is n ...

Utilizing dependency injection within an Angular 1 TypeScript application

Seeking assistance with integrating angular-jwt with typescript in my angular1 project. The angular-jwt package was installed using the following command: typings install dt~angular-jwt --global The package is located in typings>globals>angular-jwt ...

Can the tooltip placement be adjusted in ng-bootstrap when it reaches a specific y-axis point?

Currently, I am facing an issue with my tooltip appearing under the header nav-bar instead of flipping to another placement like 'left-bottom' when it reaches the header. Is there a way to manually set boundaries for tooltips in ng-bootstrap? Unl ...

Is there a way to test the syntax of mocking a service in Angular 2 to call a local json-server instead of a remote endpoint?

I am currently working on writing a unit test to verify that a property in my Angular 2 component is populated after a service call that returns a promise. Within my component, there is a method: getListItems() { this.employeeService.loadEmployees(). ...

Do you have to use "new MyClass" when initializing an array in Typescript?

In this example, I am creating a class called Person. I have opted to use a class instead of a type alias because the constructor for this class is more complex and contains functions. class Person { name: string; age: number; constructor(name ...

Disregarding axios error due to invalid certificates while developing a visual studio code extension

I'm currently developing a Visual Studio Code extension that involves making HTTPS GET requests. I'm working on ignoring invalid certificates, specifically expired certificates. Below is a simple TypeScript script that successfully achieves this ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Creating a TypeScript class without using the prototype method

Recently delving into TypeScript and encountering a perplexing issue for which I can't seem to locate a satisfactory explanation... Let's suppose I have a function: function test() { function localAccessMethod() { console.log(' ...

Should I write out the typescript .d.ts file by hand or generate it automatically

When using Typescript, you can utilize the "declaration": true" option in tsconfig to automatically generate d.ts files from your existing Typescript code. Although they may not be as concise as manually written ones, I am curious if there is any downside ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Anticipating outcome in NgRx Effects

Incorporating ngrx-effects into my project has been successful for retrieving data: component dispatches action -> effect triggers http service call -> data is returned from http service -> effect sends data to store through action -> component ...

What steps can I take to resolve the warning about '[cdkFocusInitial]' not being focusable that arises when running a Jest unit test for a material dialog component using cdkFocusInitial?

Currently, I am in the process of running Jest unit tests on a material dialog component. Within this dialog, there is an input element with the attribute cdkFocusInitial. While this setup functions perfectly when the application is running, issues arise w ...

Converting a string value into an object in Javascript using a command that functions similarly to eval in Python

When working with Python, the stringValue variable is often assigned as a string: stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}' To convert this string into a Python di ...

What exactly does RouteComponentProps entail?

While exploring information on React, I came across the term RouteComponentProps. For example: import { RouteComponentProps } from 'react-router-dom'; const ~~~: React.FC<RouteComponentProps> and class BookingSiteOverview extends React.Com ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

Is it possible to display Angular Material Slider after the label?

Searching through the Angular Material docks, I came across the Sliders feature. By default, the slider is displayed first, followed by its label like this: https://i.sstatic.net/C5LDj.png However, my goal is to have the text 'Auto Approve?' sh ...

You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved? The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argume ...