Developing interconnected dropdowns in Angular 8 for input fields

Imagine we have a list of names structured like this:

nameSelected: string;

names: Name[
    {firstName: 'John', middleName: 'Danny', lastName: 'Smith'}, 
    {firstName: 'Bob', middleName: 'Chris', lastName: 'Lopes'}, 
    {firstName: 'Gary', middleName: 'Tom', lastName: 'Harrison'}
];
<mat-form-field appearence="fill">
    <mat-label>First Name</mat-label>
    <mat-select [(value)]="nameSelected">
    <mat-option *ngFor="let name of Names" [value]="Name.firstName">{{Name.firstName}}</mat-option>
    </mat-select>
</mat-form-field> 

<mat-form-field>  
    <input matInput placeholder="Middle name" [value]="Name.middleName">{{Name.middleName}}/>
</mat-form-field> 

<mat-form-field>  
    <input matInput placeholder="Last Name"[value]="Name.lastName">{{Name.lastName}}/>
</mat-form-field>

I aim to achieve that when I choose the first name from the dropdown, the other two input fields should automatically display the corresponding middle name and last name from the array.

For instance, if John is selected, then the middle name field will show Danny and the last name field will show Smith.

Answer №1

It's a good practice to replace nameSelected as a string with an instance of the Name class. This way, you can easily access the attributes of the selected name in the other input tags. Additionally, there seems to be a small syntax error in your array creation:

.ts
// Creating an instance of type Name
nameSelected: Name = {firstName: '', middleName: '', lastName: ''};
names: Name[] = [
    {firstName: 'John', middleName: 'Danny', lastName: 'Smith'}, 
    {firstName: 'Bob', middleName: 'Chris', lastName: 'Lopes'}, 
    {firstName: 'Gary', middleName: 'Tom', lastName: 'Harrison'}
];

.html
<mat-form-field appearance="fill">
        <mat-label>First Name</mat-label>
        <mat-select [(value)]="nameSelected">
       <mat-option *ngFor="let name of names" [value]="name">{{name.firstName}}</mat-option>
        </mat-select>
    </mat-form-field> 

 <mat-form-field>  
      <input matInput placeholder="Middle name" [value]="nameSelected.middleName">
    </mat-form-field> 

 <mat-form-field>  
      <input matInput placeholder="Last Name" [value]="nameSelected.lastName">
    </mat-form-field> 

Answer №2

Your assistance in connecting the 3 boxes with the name instance was exactly what I needed. Grateful for your help!

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

Using Vue.js 3 and Bootstrap 5 to Create a Custom Reusable Modal Component for Programmatically Showing Content

Trying to develop a reusable Modal Component using Bootstrap 5, Vuejs 3, and composible API. I have managed to achieve partial functionality, Provided (Basic Bootstrap 5 modal with classes added based on the 'show' prop, and slots in the body a ...

Unable to log out of OIDC-client due to an error: end session endpoint not found

Currently, I am in the process of setting up a code flow with Auth0 as my chosen identity provider. Successfully, the sign-in process functions well and I receive a valid token from Auth0. However, I am encountering an issue when attempting to sign out ...

Adapt button functionality according to selected dropdown value in Angular

I have implemented a License Key generation process in my application where user input is used to create a unique key that is then passed to the Java backend. The code snippet for generating the key is as follows: @PostMapping("/generate") public Li ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

The type '{} is not compatible with the type 'IProps'

In my current project, I am utilizing React alongside Formik and TypeScript. The code snippet below demonstrates my usage of the withFormik Higher Order Component (HOC) in my forms: import React from 'react'; // Libraries import........ import { ...

What is the method to make a String bold when sending it through a messaging service?

Here is the structure of my service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); ...

Error message when using Typescript with Redux Saga: "Cannot use 'then' property on type 'void'. TS2339"

Whenever I attempt to fetch data from this API endpoint using promises, I encounter these type of issues. export function* signUpWithEmail(authInfo: any) { const { email, password } = authInfo.payload try { const response = yield authSignUpService ...

Tips for integrating Pico CSS into the overall scss stylesheet of your Angular project

After setting up a fresh Angular 17 project using SCSS for the stylesheet format, I decided to integrate Pico CSS into my development. However, implementing it according to the instructions in the Pico CSS documentation led to an error: ✘ [ERROR] Can&apo ...

Troubleshooting Next.js 14.1 Pre-rendering Issue: A Step-by-Step Guide

I just updated my Next.js from version 14.01 to 14.1 and encountered an error during the build process of my application. How can I resolve this issue? The error message reads as follows: Error occurred while prerendering page "/collections". For more inf ...

Having trouble retrieving the URL from the router in Angular 2?

Whenever I try to access the URL using console.log(_router.url), all it returns is a / (forward slash). Here is the code snippet in question: constructor( private el: ElementRef, private _auth:AuthenticationService, @Inject(AppStore) private ...

Issue with implementing JQuery datepicker within Angular 7 CLI application

I've been working on my application and trying to implement the jQuery datepicker functionality. It's an Angular CLI app, and I have installed jquery-datepicker and jquery using npm. Here is a snippet of the dependencies in my package.json: "@a ...

Is it time to end my MediaObserver subscription in flex-layout for Angular?

Within my Angular component, I have implemented the following code to display different elements based on screen resolution: constructor(private mediaObserver: MediaObserver) {} private mySubscription: Subscription; public ngOnInit(): void { this.my ...

Resolving the Issue: How to Solve the "Missing Required Request Body" Error in Angular and Spring MVC

I'm encountering an issue with removing a product from the database using Angular on the frontend. The error message I am receiving is: Required request body is missing: public boolean prodcust.controller.DeleteController.deleteProduct(java.lang.Stri ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...

What are the advantages of using any type in TypeScript?

We have a straightforward approach in TypeScript to perform a task: function identity(arg) { return arg; } This function takes a parameter and simply returns it, able to handle any type (integer, string, boolean, and more). Another way to declare thi ...

Provide users with the option to select the email they want to use for signing up while utilizing Angular Firebase's Google signup

My implementation involves using Angular with Firebase for sign up with Google. var result = await this.afAuth.auth.signInWithPopup( new auth.GoogleAuthProvider() ); When I visit my website in Google Chrome while logged into multiple Gmail accounts ...

Removing data based on various criteria in Prisma

While I understand that the where clause in Prisma requires a unique input for its delete operation, I have utilized the @@unique function to ensure that multiple conditions need to be columns together and must be unique. However, I am struggling with how ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...

How can I replace this jQuery state change with the appropriate Angular code?

Within a component, I have a subject that triggers a .next(value) and initiates the following jQuery logic: if (this.isOpen) { jQuery(`#preview-${this.index}`). stop().slideDown('fast'); } else { jQuery(`#preview-${this.index}` ...

Using React MUI Select in combination with react-hook-form does not seem to be compatible with Cypress testing

Within my React application, I have implemented a form that includes a dropdown select. Depending on the option selected from the dropdown, different input fields are rendered. const [templateType, setTemplateType] = useState(""); const { regi ...