Is there a way to store the selected item from a dropdown list in Angular 2?

I am struggling with saving the selected item from a dropdown list. Below is the code I have been working on. Currently, I am able to console.log the values of selectedProject.id and selectedProject.name using a button and the function outData. However, I am unable to display the value of selectedProject.name in the HTML by itself.

Whenever I try to print this data, I encounter the following error:

EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/home.component.html:2:48 caused by: self.context.selectedProject is undefined

 import { Component, OnInit, NgModule } from '@angular/core';
    import { Router, Routes, RouterModule, ActivatedRoute } from '@angular/router';
    import { FormsModule } from '@angular/forms';

    import { Project } from './project'
    import { AVAILABLEPROJECTS } from './mock-projects';

    @Component({
        moduleId: module.id,
        templateUrl: 'home.component.html',
        styles: [`
            .container {
                 padding-top: 41px;
                 width:435px; 
                 min-height:100vh;
            }
        `]
    })

    export class HomeComponent {
        public projects: Project[];
        public selectedProject: Project;

        constructor() {
            this.projects = AVAILABLEPROJECTS;
        }

        outData() {
            console.log(this.selectedProject.id);
            console.log(this.selectedProject.name);
        }
    }


<div class="container">
  <form class="form form-login" role="form">
    <h2 class="form-login-heading">Project:</h2>
    <!--{{selectedProject.name}}-->
    <div class="form-group">
        <select class="form-control" [(ngModel)]="selectedProject" name="selectedProject">
            <option *ngFor="let project of projects" [ngValue]="project">{{project.name}}</option>
        <!--[value]="project"-->
        </select>

    </div>
    <div>
        <dutton (click)="outData()">Out Data</dutton>
    </div>
  </form>
</div>

Answer №1

const chosenProject: Project = new ProjectSelected();

as well as

<option *ngFor="let proj of possibleProjects" [ngValue]="proj">{{proj?.title}}</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

When using TypeScript, the ReactDOM.render function may not accept certain components

Summary In my TypeScript and React project, I have created the AppContainer.tsx component and exported it as default. In the file app.ts, where I am using ReactDOM to render it on the targeted dom element, I encounter some errors (refer to the image). For ...

Discovering the ReturnType in Typescript when applied to functions within functions

Exploring the use of ReturnType to create a type based on return types of object's functions. Take a look at this example object: const sampleObject = { firstFunction: (): number => 1, secondFunction: (): string => 'a', }; The e ...

"Encountering a situation where a Typescript function becomes

I am experiencing an issue with the binOp function in my code. The function runs once when called from an expression, but then becomes undefined when called by term. I'm having trouble figuring out why this is happening. I've tried to debug it an ...

Utilizing winston to generate multiple log files with set maximum sizes and daily rotation

Currently, I am utilizing winston for logging with a maximum size and daily rotation. I am interested in having this functionality with one file per API endpoint to define multiple log files. Is there a way to achieve this? Displayed below is my winston ...

The compatibility issue between Bootstrap and Angular 2 is causing some challenges

Hey there, I recently enrolled in an Angular 2 course on udemy and everything was running smoothly until I encountered an issue while trying to install bootstrap. I followed the installation steps diligently, but whenever I attempt to add any bootstrap el ...

Can my https.post function determine the specific API function to call?

Here is the code for my service file that interacts with mongoDB: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { filter, isEmpty, map } from 'rxjs/operators'; import { ...

Troubleshooting Scroll Problems with Angular 5 and PDF.JS

I am working with Angular 5 and PDF.JS. Successfully downloaded a PDF and rendered it. Now, I need to display the PDF in a window by placing it inside a div. <div class="container border"> <div id="OptionsPanel" class="row lighten-1" *ngIf="isLoa ...

Steps to transform a Date object into a string in the format yyyy-mm-dd using typescript

Looking to convert a Date into a String in typescript with the format yyyy-mm-dd Currently, the date is coming up as Fri Mar 24 2017 00:00:00 GMT-0400 (Eastern Daylight Time) I just want the date to be displayed as "2017-03-24", without any time zone con ...

How to resolve 404 error for HTML files in Angular 4's "basic deployment" strategy?

I have been attempting to deploy my application following the instructions in the "Simplest deployment possible" section of the angular guide. Starting from a project created using the quick start setup, I made changes to the files index.html, main.ts, and ...

Steps for deploying a Node.js and Angular project on Heroku

Struggling to host an Angular and Node.js application on Heroku, but encountered an application error. Tried numerous solutions without success. Seeking assistance in resolving the hosting issue. 1 View logs ...

How will the presence of @types/react impact the higher-level files in my project?

https://i.sstatic.net/TfsLf.png https://i.sstatic.net/RqmMS.png Here is the structure of my directories vue node_modules src react_app node_modules @types/react package.json ...other file package.json Why does the presenc ...

Encountering problem with loading Angular2 RC1 - SyntaxError: Found unexpected token "<"

After transitioning my application from Angular 2 beta 18 to Angular2 RC1, I made changes to imports and corrected syntax errors. However, I am now encountering an error during the app loading process. Additionally, the Angular2 quickstart is not functioni ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

What is the best way to convert Angular form data into a POST request that the server can process?

In search of a solution to properly send data to the server in a format that it can accept. Currently, the title and descriptions are being successfully transmitted but the ratings are not coming through. It should be noted that there will be more than two ...

Transmit live video feed captured by getUserMedia to a Node.js server and then forward it to the Google Cloud Platform speech API

I am currently involved in a project that requires the use of the google-cloud-platform speech API. To achieve this, I am utilizing getUserMedia to acquire the MediaStream. However, I am unsure about what data I should be sending from it to the BackEnd. O ...

Tips for modifying a TypeScript object by its key value?

I am facing an issue where I have the key's value as a string and need to update the object based on this key value. Is there a method in TypeScript that can help me achieve this? I attempted to use the <object_name>[key] = value method but unf ...

How can I alter the background color of the entire header in Ionic?

Having some trouble changing the color of my header. I successfully changed the color of the white header, but not the black header where the time is displayed. I know this is beyond Ionic and part of Android, but I have seen other apps that are able to ch ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

How can I refresh and load the contents of my first tab in Angular only after reloading?

I have a situation in my Angular project where I have two tabs, and I want the first tab to be loaded by default only after a page refresh. When I click refresh, I expect the details of the first tab to show automatically instead of the second tab. Below i ...

Using template strings in one-way binding: a beginner's guide

Are you familiar with combining template strings with interpolation? This particular line is not functioning correctly. <a [href]='`#/emailing/scenario/${marketing._id}`'>{{marketing.name}}</a> Thank you! PS: I understand that the a ...