Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality?

Here's the code snippet:

<md-slide-toggle class="showToggle" name="subscribe" required></md-slide-toggle>

And here is the CSS styling:

.toggle{
  margin: auto;
}
.toggle .mat-slide-toggle{
  margin: auto auto auto 70px;
}
.toggle .mat-slide-toggle-bar{
  padding: 20px 100px;
  border-radius: 18px;
  background-color: #654898 ;
}
.toggle .mat-slide-toggle-thumb{
  padding: 10px 50px 30px 50px;
  background-color: #b755ff ;
  border-radius: 25px;
  top: 3px !important;
  border:1px solid white;
}
.toggle .mat-slide-toggle-thumb:before{
  content: 'subscribe';
  margin-left:-28px !important;
}
.toggle .mat-slide-toggle.mat-checked .mat-slide-toggle-thumb-container{
  padding: 10px 70px;
}
.toggle input[type=checkbox], .toggle input[type=radio]{
  margin: 7px 0 0 !important;
}

Finally, in TypeScript:

public device:boolean = true;

Answer №1

Here is a simple way to achieve it:

<mat-slide-toggle [(ngModel)]="device" #slider>
  {{ slider.checked ? 'Unsubscribe' : 'Subscribe' }}
</mat-slide-toggle>

SEE IT IN ACTION


If you are using an older version, just apply the following style:

.showToggle.mat-checked .mat-slide-toggle-thumb:before{
  content: 'unsubscribe';
  margin-left:-28px !important;
}

DEMO FOR OLDER VERSION

Answer №2

To enhance the styling of your elements, consider incorporating these 2 new CSS rules:

::ng-deep .toggle.subscribe .mat-slide-toggle-thumb:before{
  content: 'subscribe';
}
::ng-deep .toggle.unsubscribe .mat-slide-toggle-thumb:before{
  content: 'unsubscribe';
}

The key components to focus on are .toggle.subscribe and .toggle.unsubscribe. By adding either the subscribe or unsubscribe classes to our ul element, we can activate or deactivate these rules accordingly. This can be achieved by using [ngClass]:

<ul class="toggle" [ngClass]="{'subscribe': device, 'unsubscribe': !device}">

You have the flexibility to modify the CSS and apply [ngClass] to any other element as needed. In this instance, I presented it with a ul for demonstration purposes.

Feel free to explore the live demo here: https://stackblitz.com/edit/angular-wohxyw?file=app/slide-toggle-overview-example.html

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

Extract information from the webpage

Having my own external website, I am looking to extract data from it. Initially, I used CURL to retrieve the website's content but now I specifically need to extract the TimeStamp of a Facebook page. By inspecting the element on the page, you can find ...

"Facing issue with behaviorSubject's next() method not functioning correctly in Angular

I've developed a HeaderComponent that showcases the header and includes a search bar. When a user types something in the search bar and hits enter, they are directed to the SearchComponent. My goal is to make sure that when a user is on the Search pa ...

Retrieving the value of a formControl within a formArray is made possible through a reactive form in

How can I retrieve the value of ItemName in my HTML code? When I attempt to use {{invoiceForm.controls[i].items.controls.itemName.value | json}}, it returns as undefined. <form [formGroup]="invoiceForm"> <div formArrayName="items" *ngFor="let ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

Is it possible for jquery.find() to only target immediate children?

How can I use jQuery.find() to specifically target only the direct children of an element without selecting their descendants? Leading the selector with '>' or using '*' doesn't give me the desired result. While I know about jQ ...

Tips for transferring parameters to functions within middleware

Attempting to pass a parameter to a middleware has presented some challenges for me. Within the routes' handler, I have the following function: router.get('/users', auth.required, userController.findAll); This function then leads to the a ...

The real-time updates on an Angular 2 website can be seen across multiple devices simultaneously

Just getting started with Angular 2 and ran into an interesting issue. When setting up my website, NPM defaults the server to http://localhost:3000. To test the site on another computer, I tried accessing it using my IP address http://10.x.x.x:3000 and eve ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

Determining the Testing Status of a Node Package Management (NPM) Package

As someone who is new to Node.js and NPM, I have a question that may seem naive. Is there a method to determine if a package published on NPM has been tested? And if so, can this process be automated? Are there any tools or frameworks available that can va ...

Tips on connecting the endpoints of two parallel quadratic Bezier curves that both begin with a MoveTo command

I am currently working on creating a Sankey Diagram from scratch using VueJS and SVG. I have encountered challenges in closing the paths of two parallel quadratic Bezier curve paths from nodes to nodes. For instance, after some additional calculations, I ...

Even though I have successfully stored a key value pair in LocalStorage using JSON stringify and setItem, the data does not persist after the page is refreshed

I recently developed a Todo application that runs smoothly, except for one crucial issue - the localStorage data does not persist after refreshing the page. Initially, the localStorage operations functioned properly when there were fewer event handlers in ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Exploring the process of connecting search values in MongoDB using Mongoose

In the /search/:query route, I have the code snippet shown below: var param = { query: req.query['query'] } MyModel.find({ "$or": [ { 'name': req.param.query }, { 'age': req.param.query } ...

The Bootstrap 4 card component is a versatile and stylish

Currently working on a display layout using Bootstrap 4, specifically utilizing cards. The issue I'm facing is that the text exceeds the limit of the card, causing it to overflow. Is there a solution to make the text automatically wrap to the bottom ...

Modifying HTML attributes using AngularJS

Is there a straightforward method to dynamically alter an HTML attribute? I've used Angular's scope variable and ng-hide to hide a div, but the size of the div remains unchanged. How can I adjust the size of that particular div? I attempted th ...

Anticipate the occurrence of an event in Node.js

Is there a way to wait for an event in node js? In my bpmn workflow development, I need to execute the events step by step. Each script represents an event within the server that consists of multiple scripts. For example: 'use strict'; const Bpm ...

How many logical lines of code are in the Ubuntu operating system?

As I develop my web application, it is crucial for me to track the lines of code written in languages such as php, css, html, and JavaScript specific to the /var/www directory. However, when using the command line code counter tool, I find myself tempted ...

Initiating and pausing an Interval using a single button

I'm attempting to create a JavaScript-based chronometer that starts and stops when a single button is clicked. However, I am struggling to figure out how to properly implement the setInterval function to achieve this functionality. Below is my current ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...