Angular 4: Implementing toggle switch functionality in Angular 4 by binding boolean values retrieved from the database

Within my application, I am facing an issue with binding a toggle switch to data stored in the database. The data in the database is represented by a field called Status, which can have values of True or False. My goal is to incorporate toggle switch buttons within table rows that will display green if the status retrieved from the database is true, and black if the status is false. However, my attempts at using ngModel have not been successful. No matter what value (true or false) is stored in the database, it always displays as false when rendered on screen. To achieve the desired functionality for the toggle switch, I must use my own custom component. Below is a snippet of my code:

HTML

<ng-container *ngFor="let data of displayData$ | async; let i = index">
 <tr class= "row-break">
    <form>
     <p>
     <cm-toggle-switch [(ngModel)]="data.Status" name="switch1"></cm-toggle-switch>
    </p>
    </form>
 </tr>
 </ng-container>

DB -
export interface Data {
  {object: 1, Status: true},
  {object: 2, Status: false}
}

When I output {{data.Status}}, it correctly shows true or false as values of Status. Where could I be making a mistake in binding these values to the switch? Any assistance would be appreciated.

Toggle Switch Documentation -

<p>
    <toggle-switch [(ngModel)]="formModel.switcher" name="switch1">Main power</toggle-switch>
  </p>
  formModel: any = {
    switcher: true
  };

Answer №1

<ng-container *ngFor="let item of displayData$ | async; let index = i">
 <tr class= "row-break">
    <form>
     <p [style.color]="item.Status == true ? 'green' : 'black'">
     <cm-toggle-switch [(ngModel)]="item.Status"  name="switch1"  ></cm-toggle-switch>
    </p>
    </form>
 </tr>
 </ng-container>

Want to give this code a shot?

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

Issue with displaying first label on X axis in Bar chart using Angular and ChartJS

I'm working on creating a bar chart using ChartJS and Angular. My goal is to group the X-axis values to display only the year. https://i.stack.imgur.com/xqF21.png However, I've noticed that the first year is missing each time. In the example pr ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

My ng new project is experiencing some issues as it seems to be stuck at "CREATE project/src/app/app.component.css (0 bytes)". Can someone help

As of yesterday, my angular projects were running smoothly. However, starting today, I am facing a persistent issue where the project gets stuck without any error messages. Here is a snapshot of my terminal when the project gets stuck: C:&b ...

Displaying centered text over a mat-progress-spinner using Angular, Material, and Flex-Layout

In my Angular project, I am utilizing material and flex-layout. One challenge I encountered is centering text inside a mat-progress-spinner element. I attempted to achieve this by using position absolute, but the issue is that it doesn't stay centered ...

The FormGroup instance does not return any input method when using the get input function

I am facing an issue where a custom error message should only display if the input for foo is invalid. However, it seems like the line of code myForm.get('foo') is returning null. Below is the simplified version of component.html: <form [for ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Automate your builds with Github actions for both tags and branches!

In my typescript project repository, our release policy states that we publish packages from the master branch to the next npm tag. Additionally, we have a dedicated branch called release for publishing to the latest npm tag. My goal is to optimize the sol ...

Maintaining the order of the returned values type is crucial when working with mapped objects in Typescript

Currently, I am developing a basic mapper function for objects. This function is designed to take an array of object properties and then return an array containing the corresponding values of these properties. The function works as intended; however, I hav ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

The specified type 'MutableRefObject<HTMLInputElement | undefined>' cannot be assigned to type 'LegacyRef<HTMLInputElement> | undefined'

Consider the following simplified component : const InputElement => React.forwardRef((props:any, ref) => { const handleRef = React.useRef<HTMLInputElement|undefined>() React.useImperativeHandle(ref, () => ({ setChecked(checke ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

The import of type cannot be done within paths in tsconfig

Currently, I am tackling a server side project utilizing TypeScript. In this context, I have established various types in ooo.d.ts and configured the paths within tsconfig.json. However, upon attempting to import the specified type, an error is being displ ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

How can we create external labels for a polar chart in ng2-charts and chart.js, with a set position outside the circular rings?

Currently, I am working on creating a polar chart using Angular along with chart.js version 2.8.0 and ng2-charts version 2.3.0. In my implementation, I have utilized the chartjs-plugin-datalabels to show labels within the polar chart rings. However, this p ...

I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration. One specific route on the backend returns an array of 'Candidates': exports.list = function (req, res, next) { const sort = req.query.sort || null ...

Implementing Dynamic Component Rendering in React Native with Typescript

For the past 3 hours, I've been grappling with this particular issue: const steps = [ { Component: ChooseGameMode, props: { initialValue: gameMode, onComplete: handleChooseGameModeComplete } }, { Com ...

I am experiencing difficulties with my Angular 8 NPM package as it is unable to locate its own

I am encountering an issue where my assets are successfully copied over to my scoped npm package, but they are not available after the application is served. Currently, the images in my application are searching for a path like this: https://localhost:420 ...