Angular 2's ng-required directive is used to specify that

I have created a model-driven form in Angular 2, and I need one of the input fields to only show up if a specific checkbox is unchecked. I was able to achieve this using *ngIf directive. Now, my question is how can I make that input field required only when the checkbox is unchecked? In Angular 1.x, I could easily do this by using ng-required="condition" in the view.

Below is the HTML code:

// The Checkbox

<div class="checkbox col-sm-9">
   <label>
     <input type="checkbox" id="getCompanyAddress" style="cursor: pointer;" [formControl]="form.controls['address']">Use the company address 
  </label>
</div>

// The Optional Input Field:

<div *ngIf="form.value.address == false" class="form-group" [ngClass] = "{'has-error':!form.controls['address'].valid && form.controls['address'].touched}">
 <label for="add_gestion_adress" class="col-sm-3 control-label">Address
 </label>
  <div class="col-sm-9"><textarea rows="1" id="add_gestion_adress" class="form-control" name="add_gestion_adress" [formControl]="form.controls['address']"></textarea>
  </div>
</div>

// Model Code:

   form: FormGroup;
    constructor(fb:FormBuilder){
      this.form = fb.group({
        'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
        'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'address':[false,Validators.compose([Validators.minLength(1)])],
        'locality':[null, Validators.compose([Validators.required])],
        'county':[null,Validators.compose([Validators.required])],
        'country':[null,Validators.compose([Validators.required])]
      })

    }

Answer №1

<textarea [required]="enter your angular expression here">

This code snippet is compatible with the most recent release of Angular 4.

Answer №2

If you want to dynamically add or remove validators based on the value of a checkbox form control, you can achieve this by listening for changes in the checkbox and adjusting the validators in another control accordingly.

For example:

this.form.get('checkbox-control').valueChanges.subscribe(
      value => {

          if(value) {
              this.form.get('other-control').setValidators(Validators.required);
          } else {
              this.form.get('other-control').clearValidators();
          }

          this.form.get('other-control').updateValueAndValidity();

      }
    );

Answer №3

The FormBuilder's second argument allows for the inclusion of a validator specifically designed for cross-field validation:

this.form = fb.group({
        'name': [null, Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["bulk", Validators.compose([Validators.required, Validators.minLength(2)])],
        'person': [null, Validators.compose([Validators.required, Validators.minLength(1)])],
        'address': [false, Validators.compose([Validators.minLength(1)])],
        'locality': [null, Validators.compose([Validators.required])],
        'county': [null, Validators.compose([Validators.required])],
        'country': [null, Validators.compose([Validators.required])]
      }
    , { validator: this.customCrossFieldValidation });

The function can be customized to suit your needs.

customCrossFieldValidation(ctrl: FormGroup): ValidationErrors | null {
    let isRequired = ctrl.controls.myCheckbox.value === true;
    let hasValue = ctrl.controls.myMaybeRequiredControlXX.value;
    if (isRequired && !hasValue) return { XXrequired: true };
    return null;
}

To display or style error messages using ngClass, refer to form.errors?.XXrequired or any key returned by your customCrossFieldValidation(), rather than

form.controls.XX.errors?.required
.

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

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

Angular2: Exploring the Differences Between Observable.fromEvent and Button Click

As I work with my code, I have noticed that I am using both <button (click)="callsomefucntion" /> and Observable.fromEvent<MouseEvent>(button.nativeElement.'click') interchangeably. I am curious to understand the distinction between ...

Circular center button in the footer UI

Struggling with aligning a button in the footer perfectly? I have two icons on each side and while the UI is almost there, something seems off with the center icon's padding and shadow. I'm currently working with material-ui. Take a look at the i ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

What connections exist between systemjs.config.js and .import() in Angular2/SystemJS?

My journey to learn Angular2 has led me to various Stack Exchange posts and internet articles discussing the function of systemjs.config.js. However, I've noticed that most explanations tend to use the term "app" excessively. For example, when index. ...

Sharing data between components using $state.params and $stateParams

I have gone through several articles but none of them seem to be effective: I am trying to send some information using $state.go. This is the state configuration: .state('app.404', { url: '404', views: { 'header@&ap ...

CSS styling is not being applied to buttons within Ionic 2

I'm completely new to Ionic and hybrid apps as a whole. I've been experimenting with a test app, but for some reason, none of the CSS seems to be working. Could someone please help me figure out what mistake I might have made? Here are my files: ...

Troubles with implementing child routes in Angular 6

I'm having trouble getting the routing and child routing to work in my simple navigation for an angular 6 app. I've configured everything correctly, but it just doesn't seem to be working. Here is the structure of my app: └───src ...

Using React Testing Library with TypeScript revealed issues with ES6 modules causing test failures

I am currently working on a small project that involves React, Typescript, and Mui v5. The application is relatively small and uses the default Create React App setup. Although I am new to unit and integration testing, I am eager to make use of the tools ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

Integrating AngularJS into the Bitnami MEAN stack platform

Despite successfully activating all the JS programs for the MEAN stack, I am facing issues with Angular. I have attempted to understand the process of creating .bowerrc in my application directory, but it's proving challenging. Following the instruc ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...

Angular: Issue with canActivate not functioning properly when using redirected routes

My application's router file is set up with the following routes: export const router: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', canActivate: [AuthGuar ...

Instruction not activating

Within my main.controller.js, I have a basic json object named $scope.sections. $scope.sections = [ { id: "landing", description: "<div><img pinch-zoom src='public/img/model.png'></div>" } ]; In the vie ...

How can I show all the dates within a range of two dates using AngularJS?

How can I select "From" and "To" dates from a datepicker in AngularJS and display all the dates in between them in tabular form? ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Consider the presence of various peer dependency versions in a react-typescript library

Currently, I am in the process of converting my react component library react-esri-leaflet to typescript. This library requires the user to install react-leaflet as a peerDependency and offers support for both react-leaflet version 3 (RLV3) and react-leafl ...

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

Enhance the Angular version from 8 to 9

Looking to update my Angular version from 8 to 9 Visit this link: https://update.angular.io/#8.0:9.0l2, I am trying to execute the command : ng update @angular/core@8 @angular/cli@8 but encountering an error: The package "ng-push" has a conflicting peer ...