I would like to customize the Primeng switch by changing the values from boolean to 'N' or 'Y'

I integrated the primeNg p-switch component into my Angular 2 project. By default, the input switch's values are boolean. However, I would like to have the values set to 'N' or 'Y' instead of true or false.

@export class MyComponent{ 
         persons: Person[] = [{'name':'Marvin','legalAge': 'Y'}, {'name':'Carla','legalAge': 'N'} ] }

Here is an example implementation in the HTML template:

<p-dataTable [value]="persons">
    <p-column field="name" header="Name"></p-column>
    <p-column field="legalAge" [sortable]="true" header="is Legal Age?">
        <template let-l="rowData" pTemplate>
                <p-inputSwitch [(ngModel)]="l"></p-inputSwitch> 
        </template>
    </p-column>
</p-dataTable>

Answer №1

Keep in mind, this particular code snippet

<my-stuff [(foo)]="bar"></my-stuff>

is essentially just a more concise way of writing the following:

 <my-stuff [foo]="bar" (fooChange)="bar = $event"></my-stuff>

Whenever there's a bidirectional input involved, the output is always dictated by using the event with the Change label and $event as the assigned value. In this case, $event is boolean.

Keeping this in mind, you can utilize the p-inputSwitch component like so:

<p-inputSwitch
  [ngModel]="myProp === 'Y'"
  (ngModelChange)="myProp = $event ? 'Y' : 'N'"
></p-inputSwitch>

However, it might be something worth considering whether using strings instead of regular booleans is the best approach.

Answer №2

One way to personalize primeNg is shown in the following example

<p-inputSwitch onLabel="Yes" offLabel="No" [(ngModel)]="booleanString"></p-inputSwitch>

Update the model declaration to:

booleanString: boolean = true;

Make sure to thoroughly review the documentation

Answer №3

Because PrimeNG inputSwitch only binds as a boolean, you must create a change event function and bind your value as a string to a new property.

You can achieve this using (ngModelChange) or by using

(onChange)="handleChange($event)"
as mentioned on their website.

Here is a working example on plunker.

Check out the updated plunker for the DataTable module: link

Answer №4

Give this a shot:

 <p-inputSwitch [(ngModel)]="l" [trueValue]="'Y'" [falseValue]="'N'"></p-inputSwitch>

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 lack of compile checking for generics in Typescript?

Consider the code snippet below: interface Contract<T> { } class Deal<D> implements Contract<D> { } class Agreement<A> implements Contract<A> { } Surprisingly, the following code compiles without errors: let deal:Contract ...

"Running into Memory Limitations: Resolving System.OutOfMemoryException in ASP.NET Web API Integrated with Angular

Currently, I am working on integrating Angular 2+ with asp.net Web API. The issue I am facing is related to dealing with a C# DataTable that is being returned to Angular 2+. To do this, I am utilizing the Post method. The problem arises when I try to retr ...

What is the cause of the error message "property 'map' is undefined"?

I am currently working on a service that looks like this: public getUsers() { return this.httpClient.get(environment.BASE_URL + `api/all`); } In my component, I have implemented the ngx-bootstrap table to display the user data. import { Component, OnI ...

What is the best method for incorporating multiple collections in the get() function?

My code for university.js const mongoose = require('mongoose'); const UniversitySchema = mongoose.Schema({ worldranking:String, countryranking:String, universityname:String, bachelorprogram:String, masterprogram:String, ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

How can I modify the ngx-datatable pager component to display text instead of icons and include a totalVisible property?

I am currently customizing the datatable-pager in ngx-dataTable and have been successful in adding footers and pagers. However, I am facing two issues that need resolution: How can I display text instead of icons for the prev/Next/First and Last buttons? ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Generate a TypeScript generic function that maps class member types to class types

I am dealing with the following function in my codebase export async function batchEntitiesBy<Entity, T extends keyof Entity>( entityClass: EntityTarget<Entity> by: T, variables: readonly Entity[T][] ) { by: T, variables: readonly E ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Sending various arguments within a single post request in Angular 6 and Node.js

I am currently developing an app in Angular 6 using NodeJS + Mongoose. I have two parameters that need to be sent to the backend with a single POST request. My query is, is it possible to include both parameters in one POST Request? Thank you The paramet ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here. The ChildClass simply adds a public property called "brainPower": class ParentClass{ _me: string; constructor() { this._me = "I'm ...

Implementing TypeScript with react-router-dom v6 and using withRouter for class components

Trying to migrate my TypeScript React app to use react-router-dom version v6, but facing challenges. The official react-router-dom documentation mentions: When upgrading to v5.1, it's advised to replace all instances of withRouter with hooks. Howe ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: https://i.sstatic.net/3VBoJ.png This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { ret ...

Unable to apply "@angular/fire" using ng add command because the package does not have schematic support

Just completed the upgrade to Angular CLI 12.0.0, alongside Node 14.17.0 and npm 7.13.0 Encountering an issue when attempting to integrate Angular Fire into my project: ng add @angular/fire The following message pops up: The package @angular/[email ...

Transforming Angular 4's folder structure for improved architecture simplicity

I am faced with the challenge of organizing files and folders within an Angular 4 project in a way that allows for easy reorganization. Currently, my approach looks like this: ├───core │ │ core.module.ts │ │ index.ts │ │ │ ...