How to start Angular2 prototype with an object literal

export abstract class GridColumn {
    public field?: string;
    public sortField?: string;
    public header?: string;
    public footer?: string;
    public sortable?: any = true;
    public editable?: boolean = false;
    public filter?: boolean = true;
    public filterMatchMode?: string = 'contains';
    public filterPlaceholder?: string;
    public style?: any;
    public styleClass?: string;
    public hidden?: boolean = false;
    public selectionMode?: string = 'multiple';
    public frozen?: boolean;
}

For instance, by doing this, you will only receive an object with those specific properties.

private gridConf: GridColumn = <GridColumn>{
    field: "test2",
    header: "Test2",
    filter: true,
    filterMatchMode: "contains",
    filterPlaceholder: "Search from Test",
    sortable: true,
    selectionMode: "single"
};

The objective is to create an object of type GridColumn that includes all the declared properties along with their default values.
The following approach does not achieve this:

private gridConf: GridColumn = GridColumn({
    field: "test2",
    header: "Test2",
    filter: true,
    filterMatchMode: "contains",
    filterPlaceholder: "Search from Test",
    sortable: true,
    selectionMode: "single"
});

Using a constructor would require specifying all properties in order, which is not ideal.

The ultimate goal is to have the flexibility to define and utilize default and/or specified properties in any order like this:

private columns: Array<GridColumn> = [
    <GridColumn>{
        field: "test",
        selectionMode: "single",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        header: "Test"

    },
    <GridColumn>{
        field: "test2",
        header: "Test2",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        selectionMode: "single"
    }
];

The closest workaround found was removing the abstract keyword and adding a constructor where fields refer to itself:

public constructor(
    fields?: GridColumn) {
    if (fields) Object.assign(this, fields);
}

Answer №1

While it may not be the most conventional method, there is a workaround that could potentially achieve what you're looking for. Keep in mind that this approach may not adhere to best practices, but if you're determined to make it work, here's how you can go about it. It's worth noting that default values will only be initialized if you use new GridColumn() on a non-abstract class:

GridColumn

export class GridColumn implements IGridColumn {

    public sortable: boolean = true;
    public editable: boolean = false;
    public filter: boolean = true;
    public filterMatchMode: string = 'contains';
    public hidden: boolean = false;
    public selectionMode: string = 'multiple';

    public field: string;
    public sortField: string;
    public header: string;
    public footer: string;
    public filterPlaceholder: string;
    public style: any;
    public styleClass: string;
    public frozen: boolean;

    constructor(data: IGridColumn = {}){
       Object.assign(this, data);
    }
}

IGridColumn

export interface IGridColumn {
    public field?: string;
    public sortField?: string;
    public header?: string;
    public footer?: string;
    public sortable?: boolean;
    public editable?: boolean;
    public filter?: boolean;
    public filterMatchMode?: string;
    public filterPlaceholder?: string;
    public style?: any;
    public styleClass?: string;
    public hidden?: boolean;
    public selectionMode?: string;
    public frozen?: boolean;
}

Usage

private columns: Array<GridColumn> = [
    new GridColumn(<IGridColumn>{
        field: "test",
        selectionMode: "single",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        header: "Test"

    }),
    new GridColumn(<IGridColumn>{
        field: "test2",
        header: "Test2",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        selectionMode: "single"
    })
];

It's important to reiterate that this solution may deviate from standard best practices. Additionally, starting an interface name with an I is generally discouraged :D

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

Is there a way to access FormArray within a formGroup nested inside another formGroup?

I have a set of data structured like this: [ { id: "1", name: "task1", taskForms: [ { id: "8782", name: "ProcedureComment", sortOrder: null, descr ...

Testing specific components within an Angular 2 folder using unit tests

Our current project scenario involves: Implementing new UI changes in the project. Updating test cases for components with outdated UI test cases. Due to the presence of old UI test cases in all components, they are failing simultaneously, making it diff ...

How to use SASS mixins in Angular 5 components

Within my Angular 5 project, I have organized my SASS styles into a separate directory which contains all the variables, functions, and mixins. These are then imported into my main style.scss file. @import 'abstracts/variables', 'abstracts/ ...

Looking for an IOS yearly calendar solution for Angular6? Look no further than the angular-calendar-year-view library available at [https://github.com/MariemChaab

Seeking an angular yearly calendar for iOS similar to the one found at [https://github.com/MariemChaabeni/angular-calendar-year-view], designed for use with Angular 7. However, when attempting to integrate it into Angular 6, I encountered error ts1005; e ...

Is a date-time picker not available for use in Angular version 17?

While delving into Angular 17 and Bootstrap 5, I came across a surprising issue where the code snippet below failed to save the date and time accurately: <input type="datetime-local"> On the other hand, the following code managed to save t ...

Ways to sign up for the activeDate variable in MatCalendar so you can display the month and year labels of the current active date in the

As a newcomer to Angular, I am working on creating a datepicker with a customized header. I have successfully passed a custom header for the mat-calendar component. Reference: https://material.angular.io/components/datepicker/overview#customizing-the-calen ...

Creating a dynamic text field integrated with Google Places in Ionic 4: a step-by-step guide

I am currently implementing the google-place-api autoComplete feature in my project, but I encountered an error: TypeError: Cannot read property 'getInputElement' of undefined .html <section [formGroupName]="i" *ngFor="l ...

Encountering a TypeError while trying to use the select function with the userQuery in Angular v16 and Akita

Upon upgrading from Angular v11 to v16, Akita is causing errors in my Angular project main.js:23 ERROR TypeError: this.userQuery.select is not a function at main.js:1:262487 at u.<computed> (polyfills.js:23:32704) at A.invokeTask (polyfil ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

When utilizing two-way binding in reactive forms, the mat-select component may fail to show the selected value

Here is the code for a Reactive Form: createInputForm() { console.log('creating form'); this.instituteForm = this.formBuilder.group( { address: [this.instituteData.address, Validators.required], city: [this.institu ...

Guide on implementing Google sign in functionality in Angular 6 and redirecting on successful sign in

Seeking Clarity I recently implemented a component that presents a Google Sign In button to unauthenticated users. Upon signing in, the access token is sent to my server for verification, which then returns a jsonwebtoken. I followed Google's documen ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Unable to view loggly-winston debug logs on the user interface

I am having an issue where I cannot see any logs when calling winston.debug. It seems like the log level allowed to be seen needs to be changed. For more information, refer to the winston documentation or the Loggly node.js documentation. To start, instal ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

(iOS) Detecting input from keys with non-ascii characters captured

I am attempting to subscribe to physical keyboard events (excluding non-ASCII keys) in my app developed using the Ionic Framework (issue arises when trying to access a page launched by ionic serve, deploying the app on my iOS device, or running it in an iO ...

Having trouble with NativeScript debugging in WebStorm - breakpoints not triggering?

I am currently using WebStorm 2017.2.5 with NativeScript 3.3.1. (Check out my package.json file here) After setting up a run/debug configuration, I placed breakpoints in the following locations: However, when running the app, it does not stop at these br ...

Personalized data based on the language within Next.js

Is there a way to customize Metadata for users based on search engine keywords? To enhance SEO performance on my website, I am working on setting up unique Metadata for the two languages my website supports: English and Portuguese. Specifically, I aim to ...