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

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

several guidelines assigned to a single element

Exploring two different directives in Angular: 1. Angular UI select - utilizes isolate scope. 2. Custom directive myDirective - also uses isolate scope to access ngModel value. Encountering error due to multiple directive usage with isolate scope. Isola ...

Utilizing ngRepeat to build intricate rows within a table

I have a unique collection that appears as follows: { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, } }, "14": { "10 ...

Angular 8 - Customizing primeng/fullcalendar Appearance Based on Event Type (Looping Events) and Cell Background Color

This is how I have integrated fullcalendar into my Angular 8 application: calendar.component.ts: export class MyCalendarComponent implements OnInit { public plantedActivities: PlantedActivityModel[] public actuatorActivities: ActuatorActivityModel ...

Arrangement of items in Angular 2 array

Received a JSON response structured like this JSON response "Terms": [ { "Help": "Terms", "EventType": "Success", "Srno": 1, "Heading": "Discount Condition", "T ...

Using TypeScript: Defining function overloads with a choice of either a string or a custom object as argument

I'm attempting to implement function overloading in TypeScript. Below is the code snippet I have: /** * Returns a 400 Bad Request error. * * @returns A response with the 400 status code and a message. */ export function badRequest(): TypedRespons ...

Convert an object to nested JSON in Angular 5

I am struggling with using Angular 5 HttpClient to send a post request because I am having trouble casting an object to nested JSON. For instance, I have the following class: export class Team { members: Person[]; constructor(members: Person[]) ...

The inability to destructure the 'store' property from the 'useReduxContext(...)' because of its null value

I am currently using NextJs 13 along with redux toolkit. Whenever I run the npm run build command, I encounter this error: "Cannot destructure property 'store' of 'useReduxContext(...)' as it is null." I suspect that the issue lies wi ...

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Adjust the color of the text in Ionic based on the condition

My current solution involves highlighting text in a small slider after a user tap, but it feels very makeshift. <ion-slide *ngFor="let loopValue of values"> <div *ngIf="viewValue == loopValue"> <b> {{loopValue}} </b> ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Typescript: The art of selectively exporting specific types

As I develop a Typescript component library, the API consists of two named exports: the component itself and a helper function to create an object for passing as a prop. The process is straightforward. For this library, I utilize an index.ts file as the m ...

Cross-origin resource sharing (CORS) file uploading in AngularJS, compatible with Internet Explorer

I am looking for a simple and lightweight method to upload a small file to a REST API while utilizing CORS. I currently rely on the angular-file-upload plugin. Unfortunately, a problem arises with this plugin as it utilizes swf fallback for outdated brows ...

Ways to detect button click in a separate component

I am working with an Angular app that consists of two components: a navbar component and a display component. The navbar component has a search button that, when clicked, searches for the entered name and displays the details in the display component. I ne ...

I am having trouble retrieving the FormGroup in my nested Angular reactive form from the parent component

After watching Kara Erickson's demo of Angular forms at AngularConnect 2017 on YouTube, I was intrigued by her explanation of nested reactive forms. The issue I encountered was that no matter what I tried, I kept getting a null parentForm. Below is a ...

Injecting AngularJS together with TypeScript and Restangular to optimize application performance

Encountering an issue while trying to configure my angularjs + typescript application with the restangular plugin Here are the steps I have taken: Ran bower install --save restangular (now I have in index.html <script src="bower_components/restang ...

What are the best methods for transferring data between Angular components?

Just starting out with angular and working on a login simulation. The login component handles user authentication, receiving an api key from the authenticate web service in the response, which needs to be included in all subsequent requests. Once the use ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...