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

Encountering the following error message: "Received error: `../node_modules/electron/index.js:1:0 Module not found: Can't resolve 'fs'` while integrating next.js with electron template."

I am utilizing the electron template with next.js, and I am trying to import ipcRenderer in my pages/index.tsx file. Below is the crucial code snippet: ... import { ipcRenderer } from 'electron'; function Home() { useEffect(() => { ip ...

What are the reasons behind the unforeseen outcomes when transferring cookie logic into a function?

While working on my express route for login, I decided to use jwt for authentication and moved the logic into a separate domain by placing it in a function and adjusting my code. However, I encountered an issue where the client side code was unable to read ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

When trying to console log a selected date, the output displays as undefined

<div class='col-sm-6'> <input [(ngModel)]="date" id="date" name="date" class="form-control" required/> </div> $(function () { $('#date').datetimepicker({ format: 'DD/MM/YYYY hh:mm' } ...

Retrieve user details from a NextJS application following a successful Keycloak authentication on a Kubernetes cluster

I've been attempting to retrieve the authenticated user information in my NextJS app after being redirected to it following a successful Keycloak login on a different tab located at localhost:8080/auth. The ingress (entry point) is responsible for ch ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Tips on setting the first root element to automatically expand in a tree component

Currently, I am utilizing a tree component that includes partially loaded data. For reference, here is the link to the stackblitz example: StackBlitz. Is there a way for me to have the child element of the first root element automatically opened by defau ...

Improve Observable to prevent type assertion errors

Currently working on writing unit tests for a CanDeactive Guard, encountering a type assertion error in my jasmine spec: // Mock Guard defined at the top of the spec file class MockGuardComponent implements ComponentCanDeactivate { // Adjust this value t ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

Setting up TypeScript in Node.js

A snippet of the error encountered in the node.js command prompt is as follows: C:\Windows\System32>npm i -g typescript npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https:/ ...

What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form. How can I trigger val ...

The Angular variable binding issue persists upon reloading the page or browser, yet functions seamlessly when navigating between routes

My subscribe button displays the text "Subscribe" when the page loads, but upon reloading the page, the text disappears. The button text is controlled by TypeScript code, and strangely, when I navigate to another route, the text magically reappears. HTML ...

Remove the unnecessary space at the bottom of the Mat Dialog

I'm currently utilizing Angular Material within my Angular application. One issue I am facing is the excessive whitespace at the bottom of a dialog that displays information about a post. How can I reduce or eliminate this unnecessary space? Take a l ...

Error encountered while attempting to resume activity: TypeError - the function `callResume` is not defined in NativeScript Angular 2

When the resume event occurs, I must invoke the method this.callResume(). However, upon calling the method, a runtime error is thrown: TypeError: this.callResume is not a function I am uncertain about how to call a method from within the resume method ...

Announce enhancements to a Typescript library

Utilizing Sequency's extendSequence() feature to enhance all Sequence instances with a custom method: import Sequence, { extendSequence, isSequence } from 'sequency' import equal from '@wry/equality' class SequencyExtensions { e ...

Developing personalized modules in Angular version 6

I am diving into the world of Angular customization and I have a goal of developing a flexible module in Angular 6. My plan is to create this module and place it in the Node_modules folder so that it can be easily utilized by other teams within the organi ...

When attempting to pass an array of objects to a child component, TypeScript raises an error regarding types

Hey everyone, I'm currently facing an issue while trying to pass an array of objects as props. Here's the content of my data.json file: [ { "category": "Reaction", "score": 80, "icon": " ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...