What is the process for ensuring that the "ng-multiselect-dropdown" is a mandatory field within Angular 7?

Is there a way to require the ng-multiselect-dropdown field to have at least one selected item?

<ng-multiselect-dropdown
    [placeholder]="'Select countries'"
    [data]="countries"
    [(ngModel)]="countriesSelectedItems"
    [settings]="countriesDropdownSettings"
    (onSelect)="onItemSelect($event)"
    (onSelectAll)="onSelectAll($event)"
    name="countries"
    class="form-control">
</ng-multiselect-dropdown>

Answer №1

There was no information available regarding this on npmjs.org

Therefore, we implemented the standard method to mark any field as required in an Angular template-driven form.

relevant html:

<form (ngSubmit)='submission()'>
    <ng-multiselect-dropdown [placeholder]="'custom placeholder'" [data]="dropdownList" [(ngModel)]="selectedItems" [settings]="dropdownSettings"
     (onSelect)="onItemSelect($event)" (onSelectAll)="onSelectAll($event)" [required]='requiredField' [ngClass]='setClass()'
     name='countrySelect'>
    </ng-multiselect-dropdown>
    <p *ngIf="!requiredField">
        You must select a value !!
    </p>
    <br/>
        <button type='submit'>submit</button>
</form>

relevant TS:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 5';
  dropdownList = [];
  selectedItems = [];
  dropdownSettings = {};
  requiredField: boolean = false;

  ngOnInit() {

    this.dropdownList = [
      { "item_id": 1, "item_text": "India" },
      { "item_id": 2, "item_text": "Singapore" },
      { "item_id": 3, "item_text": "Australia" },
      { "item_id": 4, "item_text": "Canada" },
      { "item_id": 5, "item_text": "Pakistan" },
      { "item_id": 6, "item_text": "Japan" }
    ];

    this.selectedItems = [
      { "item_id": 2, "item_text": "Singapore" },
      { "item_id": 3, "item_text": "Australia" }
    ];

    this.dropdownSettings = {
      singleSelection: false,
      idField: 'item_id',
      textField: 'item_text',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 3,
      allowSearchFilter: true
    };
    this.setStatus();
  }

  setStatus() {
    (this.selectedItems.length > 0) ? this.requiredField = true : this.requiredField = false;
  }

  onItemSelect(item: any) {
    //Do something if needed
    this.setClass();
  }
  onSelectAll(items: any) {
    //Do something if needed
    this.setClass();
  }

  setClass() {
    this.setStatus();
    if (this.selectedItems.length > 0) { return 'validField' }
    else { return 'invalidField' }
  }
  submission() {
    if (this.requiredField == false) {
      /* Display a message stating that not all required fields have been filled... */
    }
    /* Perform form submission... */
  }

}

relevant css:

.validField {  border:2px solid green; display: block;  }
.invalidField {  border:2px solid red; display: block;  }

::ng-deep .multiselect-dropdown .dropdown-btn {width: -webkit-fill-available !important}
::ng-deep .multiselect-dropdown .dropdown-btn:focus {outline: none !important}

fully operational stackblitz provided here

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

Import TypeScript files with RequireJS

I'm looking for some clarification on RequireJS. Right now, I compile all my Typescript files into one JS file. If I switch to RequireJS, does that mean I won't have just one JS file anymore? As I understand it, RequireJS dynamically loads JS f ...

What is the syntax for adjusting background-position with ngStyle in Angular 4?

It's finally Friday! I'm a bit confused about how to properly set the background-position-x property in an [ngStyle] directive in Angular 4 with Ionic 3. Can someone guide me on the correct way to implement background-position-x? I expect the ou ...

Use CSS to activate a sibling div when hovering over a button within the same div that contains the button

Is it possible to change the color of div #panel when hovering over the button #button inside div #left? #left #button:hover~#panel { background-color: blue; } #panel { position: absolute; float: r ...

Mastering the utilization of API routes within the Next JS 13 App Router framework

As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13. Previously, with the Page Router, creating a single GET request involved nesting your "JS ...

Remove an element from an array within objects

Need help with removing specific items from an array within objects? If you want to delete all hobbies related to dancing, you may consider using the splice method const people = [{ id: 1, documents: [{ ...

Troubleshooting the inability to set percentage values in Bootstrap styling

My goal is to create a bar with thin bars, but my use of Bootstrap limits my control over sizes. <template> <div class="container-fluid mx-auto"> <div class="row"> <div class="square rounded-pill&qu ...

Retrieve an array containing objects with a subset of their properties. Typescript

Consider the array 'radicados' below: this.radicados = [{ id:0, asunto:'Facturas ADPRO Propias', consecutivo:'FAC-AB-00046', documentos: [{id:1, descripcion:'documento1.pdf', esAnexo:false, r ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

Can someone assist me in completing a Vertical Dots Navigation feature that activates on scroll?

I'm struggling to create a vertical dots navigation that dynamically adds the "active" class based on the section currently in view while scrolling. For example, if you are on the first section, the first dot should be white and the rest transparent. ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

Angular2 tubes sieve through hyperlinks within HTML content

As I receive HTML strings from an external source, my goal is to filter out all links that contain images, remove the href attribute, and replace it with a click event. I have attempted to achieve this using an Angular pipe, but so far I have only been suc ...

Encountering difficulties testing MatTable row population in Karma testing

Can someone please assist me in identifying the issues with my coding method? I attempted to replicate the techniques demonstrated in this tutorial on Harnesses Here is an Angular component that consists of a simple data table (MatTable) connected to a re ...

What is the best way to access a dropdown menu by clicking?

IMAGE code driver.find_element((By.XPATH, "//li[contains(@class,'ellipsis1')][1]")).click() error selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'using' must be a string if bug code change t ...

Angular Material Datatables - Issue with Paginating Data from Firestore

Data has been retrieved from Firestore and transformed into an Observable array with the InvoiceItem type. The data loads correctly onto the datatable, but there seems to be an issue initializing the paginator with the array's length. This could poss ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

The Uncaught SyntaxError issue arises when configuring webpack and Karma together

I am setting up webpack + karma + angular 2 and encountering a Uncaught SyntaxError : Unexpected token import. I am puzzled by the cause of this error. When I execute $karma start, it throws this error. Please assist me. Error START: webpack: bundle is ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

What causes an Out Of Memory error in GC during deserialization while running ng build in Angular 14?

Currently, I am working on implementing a CI pipeline in my project that involves Angular 14 and ASP.NET Core 6.0 Web API. However, when running the pipeline for a particular step, I encountered an error: Error: javascript OOM in GC during deserializatio ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

The css cropping issue with sprite image is not being resolved

I'm currently working on creating a sprite image for the bottom links on our media page, but I seem to be having trouble getting the image to crop correctly. Can anyone point out where I may be making a mistake? CSS .footer{ position:absolute; ...