Converting an object within an object into an Angular Class (Type)

Is there a way to convert the value of obj.category into the Category type as shown in the example below?

I specifically need this conversion in order to select options in a dropdown.

export class Category{
    id: number;
    name: string;

    constructor(obj: any) {
        this.id = obj.id;
        this.name = obj.name;
    }
}


export class Post {
    category: Category[];

    constructor(obj: any) {
        this.category = obj.category;
    }
}

The Category service is outlined as follows:

getCategories(): Promise<Category[]> {
    return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
  .then(response => response.json().map(obj => new Category(obj)))
  .catch(this.handleError);
}

This is how the API responds:

[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]

Template:

<select multiple name="category" [(ngModel)]="obj.post.category">
    <option  *ngFor="let category of categories" [ngValue] = "category">
       {{category.name}}
    </option>
</select>

Answer №1

One potential solution


export interface Section {
 title: string;
 description: string;
}
export class Item {
    section: Section[];
    constructor(data: any) {
        this.section = data.section as Section[];
    }
}
`

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

Creating object types in typescript from object keys: a step-by-step guide

In my JavaScript object, I have two keys named foo and bar. const x = { foo: '', bar: '' } I also have a function called abc that takes a value (which can only be either foo or bar). function abc(value: string) { const selected = x[v ...

Triggering multiple updates within a single method in Angular will cause the effect or computed function to only be triggered

Upon entering the realm of signals, our team stumbled upon a peculiar issue. Picture a scenario where a component has an effect on a signal which is a public member. In the constructor of the component, certain logic is executed to update the signal value ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...

How to display placeholder text on multiple lines in Angular Material's mat form field

Within a standard mat-form-field, I have a textarea enclosed. However, the placeholder text for this Textarea is quite lengthy, leading to truncation with an ellipsis on mobile devices due to limited space. My goal is to adjust the placeholder text based ...

Error: Unable to locate 'v8' in NextJS when using Twin Macro

I am encountering the error message Module not found: Can't resolve 'v8' when using a package in Nextjs with TypeScript. If I use a .js file, everything works fine. However, when I switch to a .tsx file, it throws a Module Not found error. ...

Exploring the capabilities of Angular 4 with the integration of the Web

Trying to integrate the Web Speech API Interfaces (https://github.com/mdn/web-speech-api/) with an Angular application (version 4.25) and an ASP Core web server. The project is built using Visual Studio 2017 (version 15.7.1). Added @types/webspeechapi type ...

Struggling with VSTS crashing during NPM Install?

My VSTS Batch Script looks like this: cd (my UI dir) echo npm install... npm install echo ng build --output-path %1\ui ng build --output-path %1\ui echo npm run ng build --output-path %1\ui npm run ng build --output-path %1\ui echo All ...

What is the best way to send information to a nested component in Angular 8?

Within an overarching HTML structure, I have various components like chart 1,2,3,4,5. Whenever the date is altered, I need to transmit that selected date to all the components. The following code represents the implementation of the event emitter between p ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

Exploring TypeScript interfaces with optional properties and returning types

As a newcomer to TypeScript, I am currently exploring the documentation and came across an example in the "Optional Properties" section that caught my attention: interface SquareConfig { color?: string; width?: number; } function createSquare(config: ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Utilizing Node modules in TypeScript, Angular 2, and SystemJS: A Comprehensive Guide

In the process of developing a simple Angular 2 application, I am constructing a class named User. This class includes a function called validPassword() which utilizes the bcrypt library to validate user passwords: import { compareSync, genSaltSync, hashS ...

Experiencing difficulty accessing the response header in Angular 16 due to CORS restrictions

When attempting to retrieve the response header from my post call, I am encountering difficulties as it appears there are "no headers" or I may be doing something incorrectly. On the backend, I am utilizing ASP.NET Core. Below is a basic outline of my API ...

Updating Angular from version 9 to 11 causes issues with router.navigate not being able to properly load a new component

After updating my Angular project from version 9 to 11 (with an upgrade to version 10 in between), I encountered a strange routing issue. In version 9, the method below worked perfectly fine. However, in version 11, although the URL changed to 'upload ...

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

Arrange the items in the last row of the flex layout with equal spacing between them

How can I arrange items in rows with equal space between them, without a large gap in the last row? <div fxFlex="row wrap" fxLayoutAlign="space-around"> <my-item *ngFor="let item of items"></my-item> </div> Current Issue: htt ...

Please indicate the Extended class type in the return of the child Class method using TypeScript 2.4

I'm currently in the process of upgrading from TypeScript version 2.3.2 to 2.4.2. In the previous version (2.3), this piece of code functioned without any issues: class Records { public save(): Records { return this; } } class User extends ...

Generating Angular components dynamically in batch

I have a collection of diverse data objects: const arr = [ {type: 'CustomA', id: 1, label: 'foo'}, {type: 'CustomB', src: './images/some.jpg'} {type: 'CustomX', firstName: 'Bob', secondNa ...

Angular Validators.pattern() does not seem to function properly, despite yielding successful results in online regex testers

I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior. This regex pattern is meant for validating the Width input of a packag ...