Submit user-specific form data in Angular 5 based on user selection

Utilizing a common reactive form to handle various types of user data, such as teachers, students, guards, etc. The form is selected from a dropdown list.

The goal is to send specific data objects based on the selected user type. A model named "User" has been created with both common and different fields. The data should be sent as follows:


selectedUser: string; //form selection like teacher
submit(data) {
  if(selectedUser === 'Teacher') {
    let teachObj = new User(data.name, data.address, data.degree);
    this.userService.post(url, teachObj);
  }
  if(selectedUser === 'Student') {
    let stuObj = new User(data.name, data.address, data.semester);
    this.userService.post(url, stuObj);  
  }
  ...and so on
}

Model class

export class User{
    //all fields here

     constructor(name: string, address: string, semester?: string, degree?: string)
}

Issue: Unable to overload constructor or create object with different parameters like in Java or C#

Answer №1

Create an interface that consists of both mandatory and optional properties, where some properties are required in specific scenarios as shown below

export interface IUser{
  name: string;
  address: string;
  semester?: string,
  degree?: string
}

In this interface, 'name' and 'address' are compulsory for all cases, while 'semester' and 'degree' can be provided based on certain conditions.

You can utilize this interface within the constructor of your User class to assign values to the properties like so:

export class User{
    //define all fields here
  public name: string;
  public address: string;
  public semester?: string;
  public degree?: string;

  constructor(user:IUser) {
    this.name = user.name;
    this.address = user.address;
    this.semester = user.semester;
    this.degree = user.degree;
  }

}

To instantiate the class, you can follow the approach below -

let data2:IUser = { name: data.name, address: data.address, degree: data.degree};
let techobj = new User(data2);

Alternatively, you can simplify it like this:

let techobj2 = new User({ name: data.name, address: data.address, degree: data.degree});

For creating an instance of Student, you can do it in the following manner -

let techobj3 = new User({ name: data.name, address: data.address, semester:data.semester });

The complete code snippet is presented below -

export interface IUser{
  name: string;
  address: string;
  semester?: string,
  degree?: string
}

 export class User{
    //define all fields here
  public name: string;
  public address: string;
  public semester?: string;
  public degree?: string;

  constructor(user:IUser) {
    this.name = user.name;
    this.address = user.address;
    this.semester = user.semester;
    this.degree = user.degree;
  }
}

let data:IUser = { name: "Niladri", address: "123", degree: "GRAD" };
let techobj = new User(data);

///OR 
let techobj2 = new User({ name: "Niladri", address: "123", degree: "GRAD" });

//Similarly 

let techobj3 = new User({ name: "Niladri", address: "123", semester:"6th" });

console.log(techobj2.degree); //GRAD
console.log(techobj3.semester); //6th

For service calls, structure them as demonstrated below -

selectedUser:string; //determine selected option such as teacher etc   
 submit(data){
   if(selectedUser === 'Teacher'){
     let teachobj = new User({ name: data.name, address: data.address, degree: data.degree});
        this.userservice.post(url,teachobj);
        }
   if(selectedUser === 'Student'){
     let stuobj = new User({ name: data.name, address: data.address, semester:data.semester });
       this.userservice.post(url,stuobj);  
      }
    ..... continue with other conditions
}

Note: Passing null for undesired parameters in the current constructor will also function correctly.

Edit 2: Another method involves creating a base class User and deriving sub-classes like Student and Teacher, then invoking super() in the child classes' constructors to transmit the name and address property values to the parent User class. However, this may result in numerous child classes depending on the number of conditionals present.

View the working demo at this link

Answer №2

To streamline your code, you could consider creating a base class called User that includes all the shared fields for both Teachers and Students. From there, you can create separate classes for Teacher and Student that extend the User class, adding their unique fields such as degree for teachers and semester for students. For more information on extending classes in Typescript, check out this resource: Extending Classes in Typescript.

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

How to efficiently eliminate duplicates from a JSON array using Angular2

Struggling with filtering my JSON array in Angular2 after transitioning from Angular 1.x. It used to be so simple using 'unique' in the filter function to remove duplicates. Here is a snippet of the JSON data: {"app":"database_1", "host":"my_h ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

An issue has been detected with the width attribute in Typescript when using

I have a question regarding the TypeScript error related to the width property. I've created a component called ProgressBar where I'm using Stitches for styling. However, TypeScript is throwing an error even when I specify the type as ANY. impor ...

Redirecting an angular application to a designated URI using nginx

I'm currently working on an Angular app that needs to be hosted on a URI like www.xyz.com/abc. I have set up an EC2 instance with nginx server running for this purpose. The website seems to be functioning well and is successfully hosted, but the probl ...

Exploring the latest features of Angular 2's ngModel form to track user selections

Consider this form: <form name="setQuestions_form" (ngSubmit)="set_questions()"> <ng-select [multiple]="true" [options]="questions" [(ngModel)]="selectedQuestions" name="selectedQuestions"></ng-select> <button>send</butt ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...

Incorrect typings being output by rxjs map

combineLatest([of(1), of('test')]).pipe( map(([myNumber, myString]) => { return [myNumber, myString]; }), map(([myNewNumber, myNewString]) => { const test = myNewString.length; }) ); Property 'length' does not ...

Angular CLI integrated with Isotope version 2

I am facing difficulties when using the isotope-layout module with Angular CLI. To install the module, I used the command: npm install isotope-layout --save After installation, I added the script in my .angular-cli.json file: "scripts": [ ... " ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

What is the best way to programmatically choose an option from a ng-select dropdown list?

My program displays a list to the user utilizing ng-select. This particular list is populated with various items: item 1 item 2 item N The user has two options when interacting with this list. They can either select an existing item or add a new one. If ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

The process of Angular Ahead-of-Time (AoT)

After reviewing the latest updates in Angular documentation, it seems that they have made significant changes to their approach. Previously, the process was as follows: Execute the ng eject command to generate webpack.config.js. Create webpack.config.aot ...

What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me. EDIT: I am currently using Passport.js and JWT ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...

Combining ctype and strlen checks in a PHP if condition

I am facing an issue with my form validation for First Name, Last Name, and E-mail. It appears that there is a problem in the validation process. Even though I validate the e-mail address successfully, the script continues processing without properly check ...

Guide to configuring an Angular Material Footer using Flex-Layout

Could someone help me with setting up the footer in my Angular Material app? I want it to: stick to the bottom when the content height is smaller than the view-port move down or get pushed down when the content height exceeds the view-port One important ...

Looking for guidance on locating Typescript type definitions?

As a newcomer to Typescript, I have recently delved into using it with React. While I have grasped the fundamentals of TS, I find myself perplexed when it comes to discovering or deriving complex types. For example, in React, when dealing with an input el ...

Displaying information in a table using Angular, instead of displaying it directly from

I'm currently developing an Angular application that utilizes ngx-datatable for displaying data. In this case, I have a Supplier object that needs to be shown in a table using ngx-datatable, with some columns displaying object properties and others sh ...

Issue with calling Angular2 and jQuery autocomplete component methods from within a spec file

Utilizing the jQuery autocomplete method within an Angular2 component, I have created a service to fetch data from an API. Below is a snippet of myComponent.ts: export class myComponent { private myVar; private binding1; private binding2; constructor( @In ...