Assigning a value to an angular material select component

I am having trouble setting the selected value of a mat-select dropdown in my component. The issue arises when I try to display services that have already been added using the same component for adding services. Despite attempting to use NgModel and specifying the service.serviceId as the value, the selected option does not appear in the dropdown. How can I make this component allow users to select services while also manually setting the displayed service with data from bookingServiceTime as the preset selected value? Any assistance would be greatly appreciated. Thank you.

     <mat-form-field>
          <mat-select placeholder="Select a service" [(ngModel)]="selectedService" required (change)="changeService($event.value)">
            <mat-optgroup *ngFor="let serviceGroup of serviceGroups" [label]="serviceGroup.serviceGroupName">
              <mat-option *ngFor="let service of serviceGroup?.services" [value]="service">
                {{service?.serviceName}}
              </mat-option>
            </mat-optgroup>
          </mat-select>
        </mat-form-field>

  ngOnInit() {
this.serviceGroupService.serviceGroups.subscribe(sg => {});

this.selectedService.serviceId = this.bookingservicetime.serviceTime.service.serviceId;
this.selectedServiceTime = this.bookingservicetime.serviceTime;
}

service.ts

export class Service extends Base {
serviceId: number;
serviceName: string;
serviceDescription: string;
serviceGroupId: number;
tax: boolean;
commission: boolean;
onlineBooking: boolean;
serviceTimes: ServiceTime[];
blockedTimeBefore?: number;
blockedTimeAfter?: number;
staff: any[]; // Need to change to StaffService.
disabled: boolean;
}

Answer №1

It appears that binding is necessary in this situation

   <mat-option *ngFor="let service of serviceGroup?.services" [value]="service.serviceName">
                {{service?.serviceName}}
   </mat-option>

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

Encountered a Timeout error with Typescript and Jest: Async callback did not execute within the 5000 ms timeout set by jest.setTimeout.Timeout

I am currently learning how to create tests using Jest with Nodejs and typescript. However, when attempting to run a simple test to check the response status, I encountered the following error: Timeout - Async callback was not invoked within the 5000 ms ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

Angular 5 - Keeping track of variable updates

I've searched various topics on this issue, but none seem to address my specific problem. I need a way to detect changes in the properties of a component without having to convert the variable into an array or iterable. I tried using Subject, but coul ...

Angular 6 Error: Unable to access property 'e4b7...f' as it is undefined

I'm encountering an issue while trying to initialize an object based on a TypeScript interface. Even though I am assigning a value, I still receive an error stating that the property is undefined. interface ITableData { domainObjectName: string; ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

When working with Angular 2, I am utilizing the canActivate method. However, even when it returns false, the application still navigates

When using canActivate in Angular2, I encountered an issue where even when it returns false, the route is still accessed. Below is my code snippet: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { this.isAuthRequi ...

acquiring environmental variables in TypeScript for node applications

I am struggling with accessing process.env variables in my TypeScript pages. It seems to be a scope issue, which doesn't make sense to me as a beginner in TypeScript. To get my environment variables, I use a YAML file and attach them to the running p ...

Return the subclass from the constructor function

class X{ constructor(input: string) { // do things } f() {console.log("X")} } class Y extends X{ constructor(input: string) { // do things } f() {console.log("Y")} } class Z extends X{ con ...

The findIndex() method will consistently return a value of -1 when used on an array

I am struggling to find a solution for the following problem. Instead of returning 1, the index is always -1 in this case. Can anyone assist me with this? let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}] let name = "b" let index = allR ...

I am wondering why the content is not showing up when using state.map(foo => <>{foo}</>) in my code

Why does the first tsx code display the state.map properly while the second code displays nothing? Despite both pieces of code performing the same task in the same way, one list is correctly displayed while the other state.map has never rendered anything, ...

Struggling to pass images from express to Angular6

Snippet of Node.js code app.use('/static/images',express.static(path.join(__dirname,'images'))) Folder Structure |-root | -images When attempting to fetch data in my Angular6+ application, I am utilizing the following ...

Symbol shortcut for changing to toString

When it comes to obtaining the numeric value of a variable like $event, typically I would use the following syntax: <ax-text-box (valueChange)='documentSearchItem.fromPrice=(+$event)'></ax-text-box> To achieve this, I simply add a +. ...

Retrieve words that begin with a specific letter

Looking to display address contents that start with the example DRACHMAN. I attempted to use match(), but it didn't work as expected. Here is my demo on Stackblitz. HTML <form (ngSubmit)="onSubmit()" #Form="ngForm"> ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

Ways to fix CSS formatting in Angular post adding Selector in your HTML

I've been working on cleaning up my code by breaking repeating code into components. However, I encountered an issue where the styling breaks after converting a chunk of code into a component and using its selector in the code. Currently, this is the ...

having issues establishing a connection between Django and Angular 2

I'm facing an issue with connecting my Angular 2 app to Django because they are running on different servers. I tried using cors but it didn't work. Any suggestions for a simple way to make the connection between them? views.py # Home Page d ...

The plugin called typescript from Rollup is throwing an error message with code TS2307. It says it cannot locate the module named 'App.svelte' or its related type declarations

I'm encountering a specific issue with my svelte project main.ts import App from './App.svelte'; const app = new App({ target: document.body, }); export default app; The first line is triggering a warning message Plugin typescript: @ ...

What is the best way to send multiple values from node.js to typescript?

My Node.js post API currently returns a token, but I want it to include the user's email, id, etc: app.post('/auth', function (req, response) { const body = req.body; console.log(req.body); let query = `select * from users wher ...