Switching buttons with AngularJS

I am currently working on a Github search app using the Github API in Angular. My goal is to make it so that when the user clicks the "Add to Favorite" button, the button disappears and the "Remove Favorite" button is displayed instead. I attempted to achieve this using active classes but since I am new to Angular, I was not successful.

Click here to view an image of the page

HTML:

  <input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()" class="input">

  <ng-template [ngIf]="profile !== '' && user">
    <div class="profileContainer">
      <div class="leftDetails">
        <img class="userAvatar" [src]="user.avatar_url" alt="User Avatar">
        <div>
          <button class="button" [routerLink]="['', user.login.toLowerCase(), user.id ]">View Profile</button>
          <button class="button" (click)="localStorage()" >Add to Favorite</button>
          <!-- <button class="button" (click)="removeLocal()" >Remove Favorite</button> -->
        </div>
        </div>

        <div class="rightDetails">
          <p><span>Username: </span>{{user.login}}</p>
          <p><span>Location:</span>{{user.location}}</p>
          <p><span>E-mail:</span>{{user.email}}</p>
          <p><span>Blog Link:</span>{{user.blog}}</p>
          <p><span>Member Since:</span>{{user.created_at}}</p>
        </div>
      
    </div>
  </ng-template>

  <div *ngIf="closeDiv">
    <div class="profileContainer" *ngFor="let item of display">
      <div class="leftDetails">
        <img class="userAvatar" [src]="item.avatar_url" alt="User Avatar">
        <div>
          <button class="button" [routerLink]="['', item.login.toLowerCase(), item.id ]">View Profile</button><br>
          <button class="button" (click)="removeLocal(item.id,item.storageKey)">Remove Favorite</button>
        </div>
      </div>

      <div class="rightDetails">
        <p><span>Username:</span>{{item.login}}</p>
        <p><span>Location:</span>{{item.location}}</p>
        <p><span>E-Mail:</span>{{item.email}}</p>
        <p><span>Blog Link:</span>{{item.blog}}</p>
        <p><span>Member Since:</span>{{item.created_at}}</p>
      </div>
    </div>
  </div>
</div>

<router-outlet></router-outlet>

TypeScript:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  local: any;
  randomNumber: any;
  randomString: any;
  idString: any;
  keys: any;
  closeDiv: boolean = true;
  isActive : boolean = true;
  constructor(private userData: HttpService) {}

  ngOnInit() {
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(this.display);
  }

  public findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      this.user = result;
    });
  }

  public localStorage() {
    this.randomNumber = Math.floor(Math.random() * 10000);
    this.randomString = this.randomNumber.toString();
    this.user.storageKey = this.randomString;
    localStorage.setItem(this.user.storageKey, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(this.display);
    console.log(this.user);
    console.log(this.user.storageKey);
  }

  public removeLocal(id: any, key: string) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
        localStorage.removeItem(key); 
      }
    } 
    console.log(key);
  }

  public detectChange(ev: any) {
    ev.length > 0 ? (this.closeDiv = false) : (this.closeDiv = true);
  }

}

Answer №1

To change the button display based on a condition, you can use the Angular *ngIf directive.

<button *ngIf='isFavoriteActive' class="button" (click)="isFavoriteActive = false; addToLocalStorage()" >Add to Favorite</button>
<button *ngIf='!isFavoriteActive' class="button" (click)="isFavoriteActive = true; removeFromLocalStorage()" >Remove Favorite</button>

Tip: Avoid using method names like localStorage to prevent conflicts with the default localStorage in JavaScript.

Answer №2

Implementing button toggle functionality with Angular.

<button class="toggle-button" (click)="isToggled = !isToggled" [ngClass]="{'active': !isToggled}" (click)="saveToLocalStorage()" >Add to Favorites</button>
<button class="toggle-button" [ngClass]="{'active': isToggled (click)="removeFromLocal(user.id,user.storageKey)" (click)="isToggled = !isToggled" >Remove from Favorites</button> 

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

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

Utilizing Gulp variables to create dynamic destination file names?

As a newcomer to gulp, I am curious about the feasibility of achieving my desired outcome. Here is the structure of my projects: root | components | | | component_1 | | styles.scss | | actions.js | | template.html | | ... | componen ...

The recent update to Bootstrap v5 caused a complete disruption in the CSS of our application

My Angular app was originally on Angular 14 and used Bootstrap with SCSS compiled to node-sass/SASS package. It also utilized ng-bootstrap v11 and Bootstrap v4.3.1 for CSS styles. As part of a general upgrade, I needed to update the Angular version to 15. ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...

How to dynamically add HTML content to a JSON string with the help of Javascript

I am working with a JSON object that includes various messages to be displayed on a webpage using Javascript. This JSON file is located in a separate directory and I have full control over it, being loaded asynchronously. There are specific cases where di ...

Cycle through the list and populate the table with the data

My attempt to clarify this explanation is my best, as articulating exactly what I am trying to achieve is quite challenging: Initially, I have a list of names: { "Items": [ { "Id": 0, "Name": "Robinson" }, ...

Having trouble getting my Angular 2 project up and running

After downloading a MEAN stack project from bitbucket, I attempted to run the front end (Angular 2) locally by navigating to the angular folder and using the command ng serve. However, I encountered the following error: "The serve command requires to be ...

Loss of precision occurs when converting a BigDecimal value from a JSON

After making a network call, the backend is sending the following data: "uom" : "EA", "qty" : 1.123456789012345678 However, when this information reaches the frontend and is logged using console.log: { qty: 1.1234567890123 ...

Convert the HTML content into a PDF while retaining the CSS styles using either JavaScript or Django

Looking to create a PDF of an HTML element with background color and images. Seeking a solution, either client-side or server-side using Django/Python. Tried jsPDF on the client side, but it does not support CSS. Considering ReportLab for Django, but uns ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

How can you create a function in typescript that only allows parameters of a specific type?

Here's what I'm trying to accomplish: function validateNumber(param: ???): param is number { } If the parameter can be a number, such as number | string or number | boolean, it should be accepted by the function. However, if the type is somethin ...

What is the method for applying a Redux statement?

Experience with Redux toolkits: https://i.sstatic.net/cwu8U.png I've encountered an issue while working with Redux toolkits where I'm unable to access certain statements. I attempted the following code snippet, but it resulted in an error. c ...

Have you ever encountered the orientationchange event in JavaScript before?

When does the orientationchange event trigger in relation to window rotation completion? Is there a way to fire an event before the operating system initiates the integrated window rotation? Edit: For example, can elements be faded out before the rotation ...

A versatile function catered to handling two distinct interface types within Typescript

Currently, I am developing a React application using TypeScript. In this project, I have implemented two useState objects to indicate if an addon or accessory has been removed from a product for visual purposes. It is important to note that products in thi ...

The Angular application is showing "&#40" instead of "("

When I make an HTTP request and receive JSON data, I encounter a problem when displaying it in my HTML using curly braces {{}}. Certain characters like "(" appear as "&#40". Is there a way to convert these special characters back to their normal form? ...

Enhance your angular application with universal support using the CLI for Angular 6

After creating a new Angular6 application using Angular CLI, I used the following command: ng generate universal This added support for Universal rendering. Everything is working fine, but I noticed that it also added the following code to my angular.jso ...

Navigating with Angular 6 - Utilizing Query Parameters within a designated secondary router outlet

Is it feasible to implement query parameters within a secondary named router outlet in Angular 6? An illustration of the desired URL format is localhost:4200/home(sidebar:chat?animal=dog) I aspire to set the query parameter "animal" and retrieve its valu ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

What could be causing the tooltip to not function properly with data-html="true"?

I am having trouble with customizing a tooltip. The data-html="true" attribute is not working as expected, and I can't seem to figure out what the issue is. .tooltip-custom { display: inline; position: relative; } ...