Passing user inputs from the view to the component in Angular 15

I'm new to Angular and currently developing a project with Angular 15. In my .ts component, I am fetching information from an API:

export class CustomPersonalSettingsComponent implements OnInit {
  

    constructor(
        private personalSettingsService: PersonalSettingService,
        private config: ConfigStateService,
        private route: ActivatedRoute
      ){}
    
      ngOnInit() { 
        const currentUserId = this.config.getOne("currentUser").id;
    
        this.personalSettingsService.get(currentUserId).subscribe((settings) => {
          this.personalSettings = settings;
            })
      } 
    }

The received entity is stored in the this.personalSettings object which has the following structure:

export interface PersonalSettingDto extends EntityDto<string> {
  userName?: string;
  email?: string;
  name?: string;
  surname?: string;
  phoneNumber?: string;
  selectedTimeZone?: string;
  timeZoneList: TimeZoneDto[];
}

Now, I want to display the received data in input fields in my HTML view. Here's the HTML template I've created for this purpose:

<div class="mb-3 ng-star-inserted">
  <label for="username" class="form-label ng-star-inserted">User name</label>
  <input ng-model="" class="form-control ng-pristine ng-valid ng-star-inserted ng-touched" id="username" autocomplete="off"
    type="text">
</div>
<!-- Other input fields go here -->

<button class="btn btn-primary" (click)="send()">
  <i class="fa fa-check mr-1"></i>
  Send
</button>

This button triggers the send() method in the TypeScript file:

  send(){ }

But how do I pass the data into this method? To achieve this goal of populating inputs with current data onInit function and sending data to the API, you might need to wrap everything in a form element. If you're unsure about how this works, feel free to ask for assistance.

Answer №1

To synchronize the form inputs with the personalSettings model, you must start by creating an instance of type PersonalSettingDto within your Component. Assuming that personalSettings represents a single object, despite its plural name.

export class CustomPersonalSettingsComponent implements OnInit {
  
    personalSettings: PersonalSettingDto = {} as PersonalSettingDto;

    constructor(
        private personalSettingsService: PersonalSettingService,
        private config: ConfigStateService,
        private route: ActivatedRoute
      ){}
    
      ngOnInit() { 
        const currentUserId = this.config.getOne("currentUser").id;
    
        this.personalSettingsService.get(currentUserId).subscribe((settings) => {
          this.personalSettings = settings;
            })
      } 
    }

To bind the model to the HTML page using ngModel directives, follow the example below to ensure synchronization between the model and user inputs.

<div class="mb-3 ng-star-inserted">
  <label for="username" class="form-label ng-star-inserted">User name</label>
  <input [(ngModel)]="personalSettings.userName" class="form-control ng-pristine ng-valid ng-star-inserted ng-touched" id="username" autocomplete="off"     type="text">
</div>
<div class="w-50 d-inline">
  <div class="mb-3">
    <label class="form-label" for="name">Name</label>
    <input  [(ngModel)]="personalSettings.name" type="text" class="form-control ng-pristine ng-valid ng-touched" id="name" name="name">
  </div>
</div>
<div class="w-50 d-inline">
  <div class="mb-3">
    <label class="form-label" for="surname">Surname</label>
    <input  [(ngModel)]="personalSettings.surname" type="text" class="form-control ng-untouched ng-pristine ng-valid" id="surname" name="surname">
  </div>
</div>
<div class="mb-3 d-inline-block w-50 ps-4 ng-star-inserted"></div>

<div class="mb-3 ng-star-inserted">
  <label for="email-address" class="form-label ng-star-inserted">Email address* </label>
  <input  [(ngModel)]="personalSettings.email" class="form-control ng-untouched ng-pristine ng-valid ng-star-inserted" id="email-address" autocomplete="off" type="text">
</div>

<div class="mb-3 ng-star-inserted"><label for="phone-number" class="form-label ng-star-inserted">Phone number</label>
  <input  [(ngModel)]="personalSettings.phoneNumber" class="form-control ng-pristine ng-valid ng-star-inserted ng-touched" id="phone-number" autocomplete="off"
    type="text">
</div>
<div class="form-group">
  <label for="priority">Time Zone</label>
  <select  [(ngModel)]="personalSettings.selectedTimeZone" class="form-control">
    <option [ngValue]="null">Select your time zone</option>
    <option *ngFor="let timeZone of personalSettings.timeZoneList" [ngValue]="timeZone.id">
      {{ timeZone.name }}
    </option>
  </select>
</div>
<button class="btn btn-primary" (click)="send()">
  <i class="fa fa-check mr-1"></i>
  Send
</button>

Now, once the form inputs are bound to the personalSettings model, they will be accessible within the send() function for validation or further processing.

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

Dealing with Dependency Injection Problem in Angular 6

I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it: @NgModule({ providers: [ ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Service B is receiving query parameters from Service A in a peculiar object format, leaving us puzzled as to the reason behind this unexpected structure

Issue: Encountered a strange bug when our service A (using laravel php) makes a call to an endpoint in service B (built with nodejs typescript + ajv + nestjs). Further explanation of the issue below. Below is an example of code in service A for constructi ...

What could be the missing piece? The function is expected to provide a return value

Currently, I am developing a Typescript Express API and encountering an issue with one of my methods. The problem arises when trying to handle data received in a callback function. public async getAll(): Promise<GeneralResponse> { locationsRe ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

Using an array of functions in Typescript: A simple guide

The code below shows that onResizeWindowHandles is currently of type any, but it should be an array of functions: export default class PageLayoutManager { private $Window: JQuery<Window>; private onResizeWindowHandlers: any; constructor () { ...

Issue: Unable to resolve all parameters for TypeDecorator in Angular 2 RC-6

I've been struggling with this error for more than a day, and I can't seem to figure out the cause. app.module import {NgModule} from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {AppComponent} from "./app.co ...

Transform a collection of interfaces consisting of key-value pairs into a unified mapped type

I have a set of interfaces that describe key-value pairs: interface Foo { key: "fooKeyType", value: "fooValueType", } interface Bar { key: "barKeyType", value: "barValueType", } interface Baz { key: "bazKeyType", value: "bazValue ...

Tips for optimizing file sizes in an Angular 11 app for production deployment

Currently, I am troubleshooting an issue with my application where some of my production files are taking a long time to load. I have already deployed my application and tried using the --aot and optimizer commands during the production build process. Here ...

What causes the form to consistently show as invalid once it has been submitted?

register.html : <form [formGroup]="signupForm" (submit)="onSubmit()" class="form-detail"> <h2>Registration Form</h2> <div class="form-row-total"> <div class="form-row"> <in ...

mat-slider: experiencing delay in updating while dragging it

Incorporating @angular/material in my Angular 5 application has been quite the journey. The specific version of Angular Material that I have implemented is 5.0.2, along with @angular/animations 5.1.2. My usage of the slider component is rather straightfor ...

Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called? globalvars.ts; httpgetmethod(url:string) { var veri; var headers = new Headers(); headers.append(' ...

Can we resolve the warnings arising from third party dependencies in a React application?

After running the pnpm install command to set up dependencies for a react app today, I encountered the following warning messages: > pnpm install  WARN  deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f18287969 ...

Unable to simulate the navigator.language

I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to f ...

Error in TypeScript: The type 'Ticket[] | undefined' is not recognized as an array type

How can I add a new item to an array of objects in React state using TypeScript? Here is the code snippet in question: export type AppState = { tickets?: Ticket[], } export type Ticket = { id: string, title: string; } export type ApiC = { ...

Error in Angular service: receiving undefined value

logdetail.service.ts import { Injectable } from '@angular/core'; import { LogDetail } from './logdetail.model'; import { HttpClient } from "@angular/common/http"; @Injectable({ providedIn: 'root' }) export class LogdetailSe ...

"Using rxjs, a value is delivered within the subscribe function

function createSingleMapService(mapServiceFactory) { return mapServiceFactory.switchSingleMapService().subscribe((service)=>{ return service }) } This snippet is a factory function in Angular that creates a single map service. The 's ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...