Tips for including or excluding a bootstrap "active" class within an Angular 4, Typescript 2 environment

Struggling to integrate my Bootstrap Framework with Angular 4 - Typescript, I am facing difficulty in getting my Tabbed Registration Form to function correctly.

In Bootstrap, this is the JS file that manages the addition and removal of the active class upon clicking on my tabbed form.

$(document).ready(function(){
$('.toggle').on('click', function() {
  $('.container').stop().addClass('active');
});

$('.close').on('click', function() {
  $('.container').stop().removeClass('active');
});

});

HTML File

<div class="container">
    <div class="row">

<!-- Mixins-->
<!-- Pen Title-->
<div class="pen-title">
  <h1>Material Login Form</h1>
</div>
<div class="container">
  <div class="card"></div>
  <div class="card">
    <h1 class="title">Login</h1>
    <form>
      <div class="input-container">
        <input type="text" id="Username" required="required"/>
        <label for="Username">Username</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Password" required="required"/>
        <label for="Password">Password</label>
        <div class="bar"></div>
      </div>
      <div class="button-container">
        <button><span>Go</span></button>
      </div>
      <div class="footer"><a href="#">Forgot your password?</a></div>
    </form>
  </div>
  <div class="card alt">
    <div class="toggle"></div>
    <h1 class="title">Register
      <div class="close"></div>
    </h1>
    <form>
      <div class="input-container">
        <input type="text" id="Username" required="required"/>
        <label for="Username">Username</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Password" required="required"/>
        <label for="Password">Password</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Repeat Password" required="required"/>
        <label for="Repeat Password">Repeat Password</label>
        <div class="bar"></div>
      </div>
      <div class="button-container">
        <button><span>Next</span></button>
      </div>
    </form>
  </div>
</div>
    </div>
</div>

Below is the TS File snippet where I attempted to adapt the code to make the Tab work without success.

clicked(event) {
    event.target.classList.add('active'); // To ADD
    event.target.classList.remove('active'); // To Remove
    event.target.classList.close('click'); // To check
    event.target.classList.toggle('click'); // To toggle
  }

I am aware that there is an error in my approach somewhere, as I am unable to get it to function properly, even though it worked fine in Bootstrap 3 with JS.

Answer №1

Try implementing it in this manner

<div class="wrapper" [ngClass]="{'active': wrapperActive}">

Next, in the TypeScript file

Start by initializing the variable:

wrapperActive=false

Then modify it as needed.

toggle(event) {
     this.wrapperActive=!this.wrapperActive
}

For further details on ng-class

Answer №2

Implement ngClass based on a condition.

Providing an updated solution to address the user's inquiry in the comments section

You can utilize Angular's (click) event listener to trigger a function without requiring jQuery. In the given example, upon clicking the element (button or any other type), the handleClick() function will be executed in Typescript and will include the event object. By extracting your property from the event, you can determine how to manipulate the ngClass class accordingly.

HTML

<button ngClass="{'active': mychoice}" (click)="handleClick($event)">
  // Add your code here
</button>

Typescript

mychoice = false; // Set it to true if you want the class initially

handleClick(event) {
    let some_case = event.something
    if (some_case === conditionToAdd) {
       this.mychoice = true;           // Condition to add
    } else {
    if (some_case === conditionToToggle) {
       this.mychoice = !this.mychoice; // Condition to toggle
    } else {
       this.mychoice = false;          // Condition to remove
    }
 }

Answer №3

The ngClass method is recommended as mentioned earlier and can be utilized if it's the sole class you require

<div class="box" [class.highlighted]="boxHighlighted">

Answer №4

After some experimentation, I discovered that it is possible to utilize jQuery within Angular if Bootstrap can seamlessly integrate with Angular.

For those who are still trying to incorporate jQuery events into Angular, here's what worked for me:

In the HTML file, I included a click event for the tab I wanted to toggle:

<div class="card alt" (click)="toggleEvent()">
..
..
</div>

In my TypeScript (TS) file, I incorporated jQuery in this manner:

declare var jquery: any;
declare var $: any;

export class AppComponent {
  title = 'Angular App';

  toggleEvent() {
    $('.toggle').on('click', function() {
      $('.container').stop().addClass('active');
    });
    $('.close').on('click', function() {
      $('.container').stop().removeClass('active');
    });

  }

}

This snippet of jQuery code adds the class active to the element with class toggle specified in the HTML. When closed, it removes the class active.

Therefore, my conventional Bootstrap 3 or 4 Framework can effectively collaborate with Angular.

Hopefully, this method assists someone in completing tasks quickly without the need to convert JS and jQuery into the Typescript paradigm.

It's important to note that Bootstrap and jQuery must be integrated with Angular via the .angular-cli.json file in your Angular directory. After initially installing bootstrap using npm install bootstrap@3, ensure that your style and scripts lines in .angular-cli.json are as follows:

"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
   "../node_modules/jquery/dist/jquery.min.js",
   "../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
......

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

What is the best way to position a material icon to the right of an input field?

Currently, I am using a mat auto complete text box with a search icon that is aligned to the left of the input. I am looking to align this search icon to the right instead. Can anyone provide assistance on how to achieve this? <mat-form-field floatLa ...

Rendering server applications using Angular 6 with Express

Currently, I am working with an Angular 6 application and Express server. I am looking to implement a server rendering system using the best practices available, but I have been struggling to find resources that are compatible with Angular 6 or do not util ...

Is it possible in Typescript to pass method signature with parameters as an argument to another method?

I am working on a React app where I have separated the actions into a different file from the service methods hoplite.actions.ts export const fetchBattleResult = createAsyncThunk<Result>( 'battle/fetchBattleResult', HopliteService.battleRe ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

I am encountering a problem with my Material UI react-swipeable-views while using TypeScript

It seems that there is a mismatch in the version of some components. import * as React from "react"; import { useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import MobileStepper from "@mui/ma ...

Insert a triangle shape at the bottom of the material design tab with the class mat-ink-bar

I'm trying to update the appearance of the mat-ink-bar in the Angular material tab. My goal is to achieve a design similar to this: Jsfiddle example The issue I'm facing is that the mat-ink-bar is already positioned as absolute, making it diffi ...

Angular - Utilizing nested arrays for efficient file uploading

I am currently working on building a file uploader using Angular. My goal is to be able to upload different types of files, with each button capable of uploading multiple files at once. However, I am running into an issue where the uploaded files are not b ...

A guide on incorporating and utilizing PhotoSwipe in Aurelia / Typescript applications

I've been attempting to integrate PhotoSwipe into my Aurelia project, but I'm struggling to get it working. Within my aurelio.json file under bundles, I've included: { "name": "photoswipe", "path": "../node_modules/photoswipe/dist/ ...

In RxJS, the map operator takes the whole array as its parameter

implement constantA = (id: string): Observable<Array<any>>=>{ } improve constantB = (id: string): Observable<Array<myClass>>=>{ constantA(metroId).map((x)=>{ return new myClass( x.FacilityName, ...

My requests and responses will undergo changes in naming conventions without my consent or awareness

Initially, I wrote it in a somewhat general manner. If you require more information, please let me know! This is how my C# class appears when sent/received on the frontend: public class Recipe : ICRUD { public Guid ID { get; set; } ...

Steps for automatically closing a TextPrompt if the end user does not respond within a specific time frame

How can I programmatically close a Prompt in Microsoft Chatbot SDK v4, such as TextPrompt or ConfirmPrompt, and end the dialog after a certain period of time if the user does not reply? I attempted to use setTimeout and step.endDialog but encountered issu ...

Can an Angular 9 application access an uploaded file through an HTTP request from the $_FILES array?

I'm currently facing an issue when attempting to send a file to a PHP server using an HTTP request in Angular 9. The problem lies in the fact that the server is not able to receive the uploaded file in $_FILES. Below is the code snippet I have written ...

Is it possible to add new values to a GraphQL query?

I am currently utilizing GraphQL and Typeorm in conjunction with an Oracle Database, specifically focusing on retrieving all data from a specific table. The query that is being executed is: SELECT "inventory"."id" AS "inventory_id", "inventory"."value" AS ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

Assign updated values to a list based on changed fields in the map

In order to track the modified fields and display them to the user, I need to identify which key corresponds to the changed field and create a new key-value pair for user visibility. log: [ 0: {type: "Changed", fields_changed: Array(2), date_modificat ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Using asynchronous functions in a loop in Node.js

Although this question may have been asked before, I am struggling to understand how things work and that is why I am starting a new thread. con.query(sql,[req.params.quizId],(err,rows,fields)=>{ //rows contains questions if(err) throw err; ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

Create dynamic breadcrumb trails using router paths

I am currently working on developing a streamlined breadcrumbs path for my application. My goal is to achieve this with the least amount of code possible. To accomplish this, I have implemented a method of listening to router events and extracting data fr ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...