How to set the default option in a select dropdown using Angular and Types

It's been a while since I last worked with Angular and now I'm tasked with working on an existing system.

I introduced an NgModal dialog to send text messages, designed as shown here:

https://i.sstatic.net/67U1M.png

Below is the code snippet I used for this implementation:

<div class="modal-content">
<div class="modal-header">
    <h5>Send Text Message</h5>
</div>

<div class="sub-title">
  <b>SELECT MESSAGE TEMPLATE:</b>
</div>

<form>
  <div>
    <select name="textmessage" class="select" [(ngModel)]="selectedMessageContentType" (change)="getSelectedTextMessage()">
        <option *ngFor="let messageContentType of messageContentTypes" [value]="messageContentType.contentId">
          {{messageContentType.messageDescription}}
        </option>
      </select>
  </div>
  <br>
  <div>
    <textarea [(ngModel)]="selectedMessageContentType.messageContent" class="textarea" maxlength="5000" type="text" name="textmessagecontent" disabled></textarea>
  </div>
</form>

<div class="modal-footer">
  <button type="button" class="btn btn-outline-primary font-weight-bold" (click)="onSendMessageClicked()">SEND</button>
  <button type="button" class="btn btn-primary font-weight-bold" (click)="onCancelClicked()">CANCEL</button>
</div>

This corresponds to the Typescript component:

import { Component, ElementRef, Input, OnInit, ViewChild } from "@angular/core";
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import { IssueService } from '../../../../services/issue.service';
import { IssueTextMessageRequestInput } from "../../../../models/inputs/issue.model";
@Component({
    selector: 'textmessage',
    templateUrl: './textmessage.component.html',
    styleUrls: ['./textmessage.component.scss']
})
export class TextMessageComponent implements OnInit {
    messageContentTypes = [
        { contentId: 50, messageDescription: 'Change', messageContent: 'Change something.' },
        { contentId: 51, messageDescription: 'Send Baseline', messageContent: 'Send Base' },
        { contentId: 52, messageDescription: 'Adapter', messageContent: 'Change to Lead Wire Adapter' }
    ];
    selectedMessageContentType: any;
    @Input() messageData: IssueTextMessageRequestInput;
constructor(private activeModal: NgbActiveModal, private issueService: IssueService) { }

ngOnInit() {
    this.selectedMessageContentType = this.messageContentTypes[0];
}

onCancelClicked() {
    this.activeModal.close();
}

onSendMessageClicked() {
    this.messageData.message = this.getMessageContentById(this.selectedMessageContentType).messageDescription;
    console.log(this.messageData);
    /*this.issueService.processAndSendMessageWithIssueActivityTracking(messageData)
    .subscribe((resp) => {});*/
}

getMessageContentById(msgId: number) {
    return this.messageContentTypes.find(content => content.contentId === msgId);
}

}

Every time I open this dialog, the dropdown menu shows up empty without setting it to the default first element in the array as intended during ngInit initialization.

Additionally, attempted to find a method to change the value in the text area dynamically based on the selection made in the dropdown. While my past experience involved using JQuery selectors for such tasks, I am restricted from utilizing JQuery in this particular project.

If anyone has any insights or assistance to offer, it would be greatly appreciated.

Thank you in advance.

Answer №1

Your value for each choice is indicated by the messageContentType.contentId:

<option 
  *ngFor="let messageContentType of messageContentTypes" 
  [value]="messageContentType.contentId">

However, you have assigned the selected option as follows:

this.selectedMessageContentType = this.messageContentTypes[0];

This implies that

this.selectedMessageContentType

Is equivalent to

{ contentId: 50, messageDescription: 'Change', messageContent: 'Change something.' }

Did you intend to do this instead?

<option 
  *ngFor="let messageContentType of messageContentTypes" 
  [value]="messageContentType">

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

Differentiating navigation design in various views of Angular 4

I am utilizing a shared navigation with content that changes via RouterModule. Is there a way to modify the design of the navigation in different views? <app-navigation></app-navigation> <router-outlet></router-outlet> For example ...

The function Observable.timer in Angular rxjs is throwing an error when imported

Encountering an error in my Angular application that reads: ERROR TypeError: rxjs_Observable__WEBPACK_IMPORTED_MODULE_4__.Observable.timer is not a function at SwitchMapSubscriber.project (hybrid.effect.ts:20) at SwitchMapSubscriber.push ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

Webpack compilation encountering an issue

I encountered an error while attempting to run my angular2 project. This issue arose after transitioning from a PC with Ubuntu to MacOS X. The Node version is 7.7.4, and the npm version is 4.1.2. I am executing npm webpack-dev-server --inline --progress ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

Obtaining Data from a Database Using Angular

I have developed a front-end website using Angular as my framework, integrated with node.js. To interact with the database, I created a "server.ts" file and connected it successfully to my DB. Now, my goal is to fetch data from the database and display i ...

Issue encountered with Typescript and Request-Promise: Attempting to call a type that does not have a call signature available

I have a server endpoint where I want to handle the result of an asynchronous request or a promise rejection by using Promise.reject('error message'). However, when I include Promise.reject in the function instead of just returning the async requ ...

The Issue with NG-Zorro Datepicker Manual Input Mask Functionality未分类

Is there a way to mask the datepicker so that users can enter dates in the format MM/dd/yyyy without typing the "/" character manually? I've tried using ngx-mask but it doesn't seem to work for the datepicker component. I have provided a link to ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

What is the best way to detect a change in a property using rxjs?

My Angular6 application has a simple input tag: <input type="text" name="searchBox" [(ngModel)]="searchTerm" class="form-control" /> I want to create an observable of the searchTerm property in order to apply operators like debounce, etc. How can I ...

No input in ng2-select2

How can I reset the value in ng2-select2 by clicking on a button? Here is my current HTML code: <select2 id="bill" [data]="colBill" [options]="option" (valueChanged)="onBillArray($event);"> The corresponding Typescript code is: this.arrBill = []; ...

What is the proper method for utilizing the --force flag in npm install when carrying out a Visual Studio publishing procedure?

Recently, while attempting to publish my Angular project in Visual Studio using a publish profile for IIS, I encountered unexpected dependency issues. This is puzzling because when running the project from the source (IIS Express), there are no such proble ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

Executing installed packages using npm: A step-by-step guide

Recently, I have encountered a confusing issue in my coding journey. In Python, I got used to installing packages and using them right away without any hiccups. For example, with SpotDL, everything worked seamlessly. However, things took a different turn w ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Angular application that features a material table created using *ngFor directive and displayedColumns defined as an array

I am trying to create a table that displays columns with the format {key: string, display: string} where 'display' is the header and 'key' is used to display the value. <ng-container *ngFor="let col of displayedColumns"> ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Navigating the structure of an Angular project: sorting modules by core, features, and

Before we begin, let me clarify that this question is original and has not been asked before. I have thoroughly reviewed the angular guide on this topic. However, I still find myself with a handful of questions. Starting with feature modules - the concept ...