Creating default selection in angular 6 using formControlName in a dropdown menu

I am currently learning MEAN stack with Angular 6 and I have a question regarding selecting the default value in a dropdown using formControlName. When updating a form, I need to have a default value in my dropdown list but I'm only getting a blank option.

Here is the TypeScript file:

export class EditBookingComponent implements OnInit {

    public currentBooking: IBooking;

    bookingid: any;
    updateBookingForm: FormGroup;
    cars: any;
    drivers: any;
    clients: any;
    
  constructor(private fb: FormBuilder,
   private bookingService: BookingService,
   private toastr: ToastrService,
   private router: Router,
   private carService: CarService,
   private driverService: DriverService,
   private clientService: ClientService,
   private route: ActivatedRoute,
   public dialogRef: MatDialogRef<EditBookingComponent>,
   @Inject(MAT_DIALOG_DATA) public data: any) { 
   
   this.bookingid = data.id;
          this.updateBookingForm = this.fb.group ({
            'clientname'  : new FormControl(""),
            'bookingdate' : new FormControl(""),
            'fromcity'    : new FormControl(""),
            'tocity'      : new FormControl(""),
            'pickupdate'  : new FormControl(""),
            'returndate'  : new FormControl(""),
            'carname'     : new FormControl(""),
            'drivername'  : new FormControl("")
        });
   }

  ngOnInit() {
   this.getOneBooking(this.bookingid);
   this.getAllCars();
   this.getAllDrivers();
   this.getAllClients();
  }
  
    getAllCars(){
      this.carService.getCars().subscribe((res) => {
          this.cars = res;
        }, err => {
          console.log(err);
        });
    }

    getAllDrivers(){
      this.driverService.getDrivers().subscribe((res) => {
          this.drivers = res;
        }, err => {
          console.log(err);
        });
    }
    
    getAllClients(){
      this.clientService.getClients().subscribe((res) => {
          this.clients = res;
        }, err => {
          console.log(err);
        });
    }
    
   getOneBooking(id){
    this.bookingService.getBooking(id).subscribe((res) => {
          this.currentBooking = res;
          this.populateForm(this.currentBooking);
        }, err => {
          console.log(err);
        });
  }
  
  populateForm(data): void {
    this.updateBookingForm.patchValue({
            clientname  : data.clientName.clientName,
            bookingdate : data.bookingDate,
            fromcity    : data.fromCity,
            tocity      : data.toCity,
            pickupdate  : data.pickupDate,
            returndate  : data.returnDate,
            carname     : data.car.carName,
            drivername  : data.driver.driverName
    });
  }
  
  editBooking(formdata:any){
    let theForm = this.updateBookingForm.value;
    this.bookingService.editBooking(this.bookingid, theForm).subscribe((res) => {
    if (res.success === false) {
            this.toastr.error(res.message);
          } else {
            this.toastr.success(res.message);
            this.router.navigate(['/admin/booking']);
            this.dialogRef.close();
          }
          this.updateBookingForm.reset();
      });
 }
    close() {
        this.dialogRef.close();
    }
}

.

html file

<form class="well form-horizontal" [formGroup]="updateBookingForm" (ngSubmit)="editBooking(updateBookingForm.value)">

  <fieldset>
    <div class="form-group">
      <label class="col-md-4 control-label">Booking Id</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span><strong>{{bookingid}}</strong></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">Client Name</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
          <select class="form-control" formControlName="clientname" required>
            <option *ngFor="let client of clients" value="{{client._id}}">{{client.clientName}}
            </option>
          </select>
        </div>
      </div>

    </div>

    <div class="form-group">
      <label class="col-md-4 control-label">Booking Date</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span><input id="bookingDate" name="bookingdate" placeholder="Booking Date" class="form-control" required="true" value="" type="text" formControlName="bookingdate"></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">From</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-upload"></i></span><input id="fromCity" name="fromcity" placeholder="From City" class="form-control" required="true" value="" type="text" formControlName="fromcity"></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">To</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-download"></i></span><input id="toCity" name="tocity" placeholder="To City" class="form-control" required="true" value="" type="text" formControlName="tocity"></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">PickUp Date</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span><input id="pickupDate" name="pickupdate" placeholder="Pickup Date" class="form-control" required="true" value="" type="text" formControlName="pickupdate"></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">Return Date</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span><input id="returnDate" name="returndate" placeholder="Return Date" class="form-control" required="true" value="" type="text" formControlName="returndate"></div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">Car</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="fas fa-car-side"></i></span>

          <select class="form-control" formControlName="carname" required>

            <option *ngFor="let car of cars" value="{{car._id}}">{{car.carName}}
            </option>
          </select>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label">Driver</label>
      <div class="col-md-8 inputGroupContainer">
        <div class="input-group"><span class="input-group-addon"><i class="fas fa-address-card"></i></span>
          <select class="form-control" formControlName="drivername" required>
            <option *ngFor="let driver of drivers" value="{{driver._id}}">{{driver.driverName}}
            </option>
          </select>
        </div>
      </div>
    </div>
    <div class="col-sm-12 controls">
      <input class="btn btn-success" mat-raised-button (click)="dialogRef.close()" type="submit" value="Update Booking" />

    </div>
  </fieldset>
</form>

I am looking for assistance on how to set default values in the client, car, and driver select options.

Answer №1

Utilize the [ngValue] attribute within your select element. For more information, refer to this documentation.

<select class="form-control" [ngValue]="vehicle" formControlName="vehiclename" required>
    <option *ngFor="let vehicle of vehicles" value="{{vehicle._id}}">{{vehicle.vehicleName}}</option>
</select>

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

Implementing OAuth2 in a Microservices architecture to establish a user account

In my current setup, I am utilizing a React Application along with a separate Express API. My goal is to allow users to register through my React app. To do this, I believe the oauth2 flows should follow these steps: Prompt the user for information (suc ...

Converting an NPM package into a gulp workflow

I'm currently generating html files from Nunjucks using my gulp file. Now, I need to convert these html files into text files. I came across a useful NPM package called html-to-text that can help with this task. However, I'm facing some challenge ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

Having an issue with `console.log` not working in the `public/javascript/` directory in Node

I've encountered an issue where console.log isn't working for me when placed within a function in the public/javascripts folder of my node.js project. My current folder structure is as follows: views routes public javascripts > utils.js Wi ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Establishing a connection between a Socket.io browser client and a Node.js Net server running locally

I have implemented a custom userscript on an HTTPS website. The script is utilizing the Socket.io client API to establish a connection with a Node.js TCP server running on my personal computer. Upon inspection, the server registers that the client is tryi ...

Transfer images from an Android device to a Node.js server by utilizing AsyncHttpClient

I am looking to send images from an android app to a node.js server for storage in MongoDB on the server side. I am using AsyncHttpClient to make a POST request. This is what my code looks like: On Android -> RequestParams param = new RequestParams(); p ...

Having difficulty gracefully stopping a node and Express app? The close function of the node http server may not finish the shutdown process

I am currently working on an app that relies on an Express.js-based server. My main concern is ensuring that all connections are properly closed before the node process exits upon receiving a shutdown signal like SIGTERM or SIGINT. To address this issue, ...

Is it possible to have more than one response for a node in the Bot framework

Currently, I am working on creating a bot through the Microsoft Bot Framework. To enhance language processing capabilities, I am incorporating Luis so that the same question can be asked in various ways. I am curious if there is a method within the bot fra ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

Developing websites with the use of MongoDB in framework

While working with Node.js / Express.js and MongoDB, I encountered some missing parts that hindered my progress in using Node.js. Could you please recommend some web development frameworks that have native support for MongoDB? I am open to learning new pr ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

Guide on utilizing schema methods with mongoose and Express

I keep encountering an issue when trying to execute user.comparePassword from exports.index.post. The issues seems to be isolated to the code provided below, which includes all relevant information. While the UserSchema.pre('save') method works w ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

When attempting to delete a row from an sqlite database, Express.js throws a "TypeError: Cannot read property 'id' of undefined" error

I'm currently working on developing a simple CRUD API. I have successfully implemented functionalities to retrieve all parts, fetch a part by its ID, and add a new part. However, I am encountering an issue with the delete part method as it keeps gener ...

Repairing a broken npm module due to an absent file

Recently, I encountered a frustrating issue on my PC where creating a file named "important.js" was blocked due to ransomware concerns. This has caused complications with certain libraries in the node.js ecosystem that require this specific file name. As a ...

Steps for installing npm on Ubuntu operating system

To set up the mocha test framework, npm is required. To install it, follow these steps: 1. sudo apt-get install npm 2. npm install -g mocha After running the first command, you may encounter the following error: user@dell:~/mochatest$ sudo apt-get in ...

Setting up NGINX to efficiently serve JPG images to a Vue.js frontend within a Docker container

I am facing a challenge with replacing npm's http-server with NGINX as a static file server when transitioning from a local setup to a dockerized environment. My current setup involves an app built using Flask + Gunicorn + Vue.js + THREE.js. The text ...