Angular 2 or more variable binding

In this demonstration, only the unit-object will be saved:

<select id="unit" name="unit" #unit="ngModel" class="form-control" [(ngModel)]="iu.unit" (change)="onDropdownChangeUnit($event)">
                  <option *ngFor="let i of UI_Units" [ngValue]="i">{{i.name}}</option>
                </select>

The final object structure can be viewed here.

The goal is to update both the unit-object and the unitID within the object during each iteration in the foreach-loop, including loading the initial value from its corresponding unitID.

Any suggestions on how to achieve this?

Update:

The object is fetched from the backend without the unit, but with the presence of unitId. The missing data like unit can be populated using UI_Units.

A) Need the ability to preselect the initial value based on iu.unitId => i(unit) (if possible)

B) Upon selecting a different i(unit), both iu.unitId and iu.unit should get updated accordingly.

Hopefully, this clarifies things further.

Answer №1

Make sure to update the HTML page with [(ngModel)]="iu" and

(change)="onDropdownChangeUnit(iu)"

<select id="unit" name="unit" #unit="ngModel" class="form-control" [(ngModel)]="iu" (change)="onDropdownChangeUnit(iu)">
     <option *ngFor="let i of UI_Units" [ngValue]="i">{{i.name}}</option>
</select>

Additionally, ensure the component page is checked as shown below

iu:any;
onDropdownChangeUnit(item){
   console.log(item);
}

Answer №2

Can you please implement the following updates?

component.html

<select id="unit" name="unit"  class="form-control"  (change)="onDropdownChangeUnit($event)">
   <option *ngFor="let item of units" [value]="item?.id">{{item?.name}}</option>
</select>

component.ts

onDropdownChangeUnit($event){
  let id = $event.target.value;
  this.selectedUnit['info'] = this.units.find((x) => x._id.toString() === id.toString());
}

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

Unable to resolve all parameters for the createRouterScroller function in Angular routing

Just starting out with Angular routing and added the package to my Ionic project using npm i @angular/router Encountering some errors after adding appRoutes to app.modules.ts RouterModule.forRoot( appRoutes, { enableTracing: true } // <-- for d ...

Encountered an error: Object(...) function not defined when using React, Formik, and Webpack

I have encountered an issue while trying to use both Formik and React-Form-Hooks in my project. Despite using Typescript as my language and Babel as the transpiler, both libraries throw the same error when compiled. Uncaught TypeError: Object(...) is not ...

The AngularJS2 component fails to render properly following the implementation of a new router

I recently encountered an issue with my AngularJS2 app component not loading after adding the router. Surprisingly, there was no error in the log. However, upon removing the router, the app started working again. Has anyone else faced a similar issue befor ...

Angular 2 - Unable to access the AssetUrl property due to undefined value

Just getting started with angular2 and material-design. Attempting to integrate the two. I decided to clone this material2-app, which is built on angular2 and material2 and ran npm install. However, when I tried running npm start to start a server, I enc ...

The function $$.generatePoint is not recognized in the Billboard.js library

Having some trouble with integrating billboard.js into my Vue project as an alternative to using d3.js. Struggling to get it working in both my repository and a vanilla Vue project. Anyone familiar with the process of getting billboard.js running smoothly ...

Adding Objects to an Array in Angular 4

I'm currently facing an issue with adding a new object to an existing array. My Objective: I want to add a newly drawn card into the current array/object. In my app.component.ts file: @Component({ selector: 'app-root', te ...

What steps should I take to display the outline of an Angular Material Icon in my Angular application?

Currently, I have <mat-icon>info<mat-icon> The result is the info icon with a filled color. However, my intention is to display just the outline of the icon. How can I achieve that? The specific icon I am looking for can be found at https:/ ...

Limiting the defaultValue of a select to one of the values of its options in TypeScript: A guide

Is there a way to configure the Select component's properties so that the defaultValue is limited to one of the predefined options values ("au" | "nz" in this scenario)? const countryOptions = [ { value: "au", l ...

Enhancing Visuals with src="imageUrl within Html"

Is there a way to customize the appearance of images that are fetched from an API imageUrl? I would like to create some space between the columns but when the images are displayed on a medium to small screen, they appear too close together with no spacing. ...

Challenges with handling click events in Angular Material's mat-sidenav-content

When I add a click event to the mat-sidenav-content element like this: <mat-sidenav-content (click)="isNavBarOpened=false">, the mat-slide-toggle inside it stops functioning. Check out the code example here ...

Testing ngrx effects action failure and how it impacts the

Having issues with this particular effect login$ = createEffect(() => this.actions$.pipe( ofType(AuthActions.login), exhaustMap((action) => this.service.login(action.credentials).pipe( map((data: LoginResponseDto) =& ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

Link Array Element to [(value)] within Angular

Hey there! I'm currently working with Angular Material and dealing with an Array of products to generate a table in my template. <tbody> <tr *ngFor="let item of productArray | async; let i = index"> Within this loop, I have another l ...

Why am I encountering numerous errors while attempting to install Juice Shop?

My attempt to install the juice shop app from GitHub resulted in 63 errors showing up after running the command npm install. [riki@anarchy]: ~/juiceShop/juice-shop>$ npm install (Various warnings and engine compatibility issues) Multiple vulnerabilit ...

Send all Apache requests within a specified URL directory to a particular file, while directing all other requests to a different file

I am in the process of setting up an Angular application along with a basic PHP CRUD API backend on my Raspberry Pi 3 using Apache. My goal is to configure the mod_rewrite rules to first check for existing files or directories, then redirect requests for t ...

Creating an Angular 2 component library that is compatible with both webpack.js and system.js: A guide

This is my first venture into creating an Angular 2 library. So far, it consists of a collection of components. I am aiming to make this library compatible with both Webpack and SystemJS. I have successfully written the code for the first component to be c ...

What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database. HTML: <tr *ngFor="let profile of profiles | async"> <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model=&apo ...

Creating composite type guards - passing down properties from the type guard to the calling function

type Bird = { fly: () => "fly" }; type Insect = { annoy: () => "annoy" }; type Dog = { beTheBest: () => "dogdogdog" }; type Animal = Bird | Insect | Dog; const isBird = (animal: Animal): animal is Bird => { if ...

Manage sequential observables and await user input

I have a collection of items that I need to loop through in order to determine whether or not a modal dialog should be displayed to the user, and then pause the iteration until the user provides input. The items are stored within an observable as Observabl ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...