Setting default values for multiple selections can be accomplished by following these steps

I am working on a form that collects information about streets and their corresponding neighborhoods:

https://i.sstatic.net/FAZLK.png

When I click on a button in the grid to edit, the street data is displayed like this:

https://i.sstatic.net/UHiLX.png

One thing I am struggling with is automatically selecting the neighborhoods that correspond to the street, like shown in the following image:

https://i.sstatic.net/IaLvy.png

Here is the HTML code snippet:

                    <form [formGroup]="frmCalle">

                    <div class="form-group">
                        <label>NOMBRE*</label>
                        <input matInput id="txtCalle" formControlName="nombre" [(ngModel)]="inputCalle" type="text" class="form-control inputAbm" placeholder="Enter Street Name">
                        <button *ngIf="inputCalle !== ''" mat-button (click)="resetForm('calle')" matSuffix mat-icon-button aria-label="Clear" matTooltip="Clear Text">
                            <i class="material-icons">clear</i>
                        </button>

                        <br><br>

                        <label>NEIGHBORHOOD</label><br>
                        <mat-select formControlName="barrio" class="form-control inputAbm" [(ngModel)]="selectBar" placeholder="Select Neighborhood" multiple>
                            <mat-option *ngFor="let item of arrBarrio" [value]="item.bar_IDBarrio">{{ item.bar_nombre }}</mat-option>
                        </mat-select>
                        <button *ngIf="selectBar !== ''" mat-button (click)="resetForm('barrio')" matSuffix mat-icon-button aria-label="Clear" matTooltip="Clear Text">
                            <i class="material-icons">clear</i>
                        </button>
                    </div>
                    <div class="form-group">
                        <div class="form-row">
                            <div class="col-md-8">
                                <button id="btnClear" (click)="registrarCalle(boBand)" [disabled]="!frmCalle.valid" class="btn btn-block btnPrimario myBtnCard">
                                    Save
                                </button>
                            </div>
                            <div class="col-md-4">
                                <button (click)="resetForm('')" mat-mini-fab class="btnFiltro" class="btnLimpiar" matTooltip="Clear Fields" matTooltipPosition="left"><i class="material-icons">clear</i></button>
                            </div>
                        </div>
                    </div>

                </form>

And here is the TypeScript code:

mostrarDataCalle(stCalle: string) {
this.inputCalle = stCalle;

const objCalle = {
  cal_nombre: stCalle
};

// QUERY TO GET ALL NEIGHBORHOODS FROM DATABASE
this.reclamoService.selectBarrioPorCalle(objCalle).subscribe(data => {
  this.arrBarrio.forEach(element => {
    // CODE TO SELECT CORRESPONDING NEIGHBORHOODS
  });
});
}

And the Entity class:

export class Barrio {
   bar_IDBarrio: number;
   bar_nombre: string;
   constructor() {}
}

Any suggestions on how to achieve this functionality?

Answer №1

Create an array containing values and then utilize setValue to assign the chosen values

selectedValues = [];
displayStreetData(streetName: string) {
this.inputStreet = streetName;

const streetObj = {
   street_name: streetName
 };

this.reclamoService.selectNeighborhoodByStreet(streetObj).subscribe(data => {
  this.neighborhoodArray.forEach(element => {
    // In this section, iterate through the elements and select the corresponding neighborhoods
    element.forEach( x => this.selectedValues.push(x) )
 });
});
   this.formStreet.get('neighborhood').setValue(this.selectedValues);
}

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

Having trouble with setting a default radio button selection in an Angular form within Ionic 4 framework

I am currently working on an application using Ionic to design a form that includes radio buttons. I have been attempting to set one of the radio buttons as checked by default, but so far, nothing seems to be effective. I have tried various methods, such a ...

Tips for adding an item to an array within a Map using functional programming in TypeScript/JavaScript

As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following ...

When using the `.push` method, the array becomes null

Currently, I am in the process of developing an angular application. Within my component's .ts file, there exists an array structured as follows: public myArray = []; public dataFromAPI = []; In a particular method within this component, whenever I ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

Leveraging Angular Observables for seamless data sharing across components

As I embark on developing my very first Angular app, I have encountered a challenge with filtering a list of book objects based on their gender attribute. The issue lies in sharing data between components – specifically the filteredData variable and the ...

Sizing the Angular CDK overlay backdrop appropriately when connecting it to a component

Is there a way to have a CDK overlay specifically cover a certain component using flexibleConnectedTo()? I am struggling with ensuring that the overlay backdrop only covers the targeted component, rather than the entire page. The CSS for the cdk-overlay-co ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Step-by-step guide on setting up a personalized validation using Formly alongside a calendar input

I have successfully implemented a custom calendar template, but I am struggling with creating validators and error messages. Most examples I found online deal with input elements, whereas my element is not an input. app.modules.ts FormlyModule.forRoot({ e ...

Contrasting the double dash without any arguments versus the double dash with a specific argument, such as "no-watch."

For instance, when attempting to run unit tests for an Angular app, the following command is used: npm run test -- --no-watch --browsers=ChromeHeadlessCI I know that two dashes (--) are required to pass arguments into the npm script. However, I'm con ...

How can one determine if a background image has successfully loaded in an Angular application?

In my Angular 7 application, I am displaying a background image in a div. However, there are instances when the link to the image is broken. The way I bind the image in my HTML is as follows: <div [ngStyle]="{'background-image': 'url(&a ...

Exploring Angular's wild comparison capabilities for strings within HTML documents

I have a question that may seem basic, but I am curious if it is possible to use wildcards in *ngIf comparisons. Consider the following code snippet: <ng-container *ngIf="test == 'teststring'"> </ng-container> I am wonder ...

What is the reason behind the lack of covariance in an interface when using a type of T[keyof T]?

I'm attempting to enable type covariance so that Type<Cat> can be treated as a Type<Animal>, for instance, treating a list of Cats as a list of Animals. However, using the type T[keyof T] in a method within the Type interface seems to hind ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

Personalize the Number Input Cell in ag-grid

Ag-grid field must only accept numbers. I have attempted some code that successfully works, but it adds two arrow buttons. field: "TotalQty", headerName: "TOTAL KIT QTY", editable: true, cellRenderer: params => { return '& ...

Unable to connect with '*ngFor' because it is not a recognized attribute of 'div'

I attempted to bind a value for filter in *ngFor, but it didn't work correctly. How can I successfully bind data to ngFor? Source code is shown below: In my .ts file, menuIcons:any[]; public pageName:any = "projects"; this.menuIcons=[{ ...

Injecting the OrderEntry context into the CartOutlets.ITEM_DETAILS outlet in Spartacus can be achieved by following these

Here is a question from a different source: Is there a way to access orderEntry while utilizing <ng-template [cxOutlet]="CartOutlets.ITEM_DETAILS"> </ng-template> placeholder from the cart-item component? It appears that without [c ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Struggling with the error message "Type 'ChangeEvent<unknown>' is not assignable to type 'ChangeEvent<MouseEvent>'" while working with React and TypeScript? Here's how you can tackle this issue

Within the App.tsx file, I encountered an issue with the Material UI Pagination component where it was throwing an error related to type mismatch. The error message stated: Argument of type 'ChangeEvent' is not assignable to parameter of type &ap ...

Discovering all subclasses of a base class in AngularWould you like to learn how

abstract class Item { private name: string; private description: string; constructor(name: string,description:string) { this.name = name; this.description = description; } } class Car extends Item { constructor(name: string,descri ...

What is the best method for transforming the value of an "input type week" into a date or numerical format?

I am currently working with an HTML5 element: <input class="form-control" #semana="ngModel" name="semana" [(ngModel)]="detalle.semana" type="week"> When I retrieve the value, it comes in the format of a string such as "2018-W23". I am looking to co ...