Is there a way to modify the button exclusively within the div where it was pressed?

I plan to incorporate three buttons in my project (Download, Edit, and Upload).

Upon clicking the Download button, a function is triggered, changing the button to Edit. Clicking the Edit button will then change it to Upload, and finally, clicking the Upload button will transform it back to Download.

The challenge I'm facing is altering the specific button on the line where it was clicked.

Although I attempted to pass the index parameter to the function, it didn't produce the desired outcome.

To toggle the visibility of buttons based on executed functions, I resorted to using JavaScript like (example)

$(".class").css({"display": "none"});
, but I believe there could be a better approach.

If anyone can offer guidance or assistance, I would greatly appreciate it.

DEMO

.html

<div *ngFor="let item of items; let i = index">
    <div class="d-flex flex-row" style="margin-top:16px">
        <div class="p-2">{{item.id}}</div>
        <div class="p-2">{{item.name}}</div>
        <div class="p-2 bg-primary" style="margin-left:auto">
            <button (click)="download()">Download</button>
            <!-- <button (click)="edit()">Edit</button>
    <button (click)="upload()">Upload</button> -->
        </div>
    </div>
</div>

.ts

items=[{
  id:1,
  name:"item1",
},
{
  id:2,
  name:"item2",
},
{
  id:3,
  name:"item3",
},]

download(){
  //change button download to button EDIT
}

edit(){
  //change button edit to button Upload
}

upload(){
  //change button upload to button Download
}

https://i.sstatic.net/oMxaD.png

By clicking the download button, I aim to run the download function() and switch the button to edit only on the respective line.

Answer №1

If you'd like to experiment, feel free to check out this link: https://stackblitz.com/edit/angular-fj5rvr-copy

In essence, we include a variable that tracks the button's current status and update it each time the user interacts with the button.

Answer №2

To change the text of a button from "Download" to "Edit", you can utilize the ViewChild variable along with Renderer2.

this.renderer.setProperty(this.downloadButton.nativeElement, "innerHTML",  "Edit");

Below is the HTML code snippet:

<div *ngFor="let item of items; let i = index">
    <div class="d-flex flex-row" style="margin-top:16px">
        <div class="p-2">{{item.id}}</div>
        <div class="p-2">{{item.name}}</div>
        <div class="p-2 bg-primary" style="margin-left:auto">
            <button (click)="download()" #downloadButton>Download</button>
            <!-- <button (click)="edit()">Edit</button>
    <button (click)="upload()">Upload</button> -->
        </div>
    </div>
</div>

And here is the TypeScript code sample:

 constructor(private renderer: Renderer2) {}
  @ViewChild("downloadButton") downloadButton: ElementRef;

  download() {
    //change button download to button EDIT
    this.renderer.setProperty(
      this.downloadButton.nativeElement,
      "innerHTML",
      "Edit"
    );
    //this.downloadButton.nativeElement.innerText = 'Edit';
  }

You can view a live demonstration at https://stackblitz.com/edit/angular-91rnzc

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

The parameter type '{ email: string; }' in NGXS does not accept arguments of type 'string'

Struggling to retrieve data from an API using ngxs with this.store.dispatch(new GetUser(userEmail)) Attempted to use the user id stored in local storage as a string and convert it to a number but encountered a similar error (Argument of type 'string&a ...

Retrieve functions with varying signatures from another function with precise typing requirements

My code includes a dispatch function that takes a parameter and then returns a different function based on the parameter value. Here is a simplified version: type Choice = 'start' | 'end'; function dispatch(choice: Choice) { switch ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

I am interested in utilizing Vue Fallthrough attributes, but I specifically want them to be applied only to the input elements within the component and not on the container itself

I am facing an issue with my checkbox component. I want to utilize Fallthrough attributes to pass non-declared attributes to the input inside the checkbox component. However, when I add HTML attributes to the Vue component, those attributes are applied not ...

How can I retrieve the value of a nested reactive form in Angular?

I'm working with a nested form setup that looks like this: profileForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl(''), address: new FormGroup({ street: new FormControl(''), ...

Using ngFor to destructure two variables simultaneously

When working with Python, I found a way to unpack both variables in each tuple at every iteration. l = [(1, 2), (4, 5), (8, 9)] for k,v in l: print("k = ", k) print("v = ", v) print("-------") # k = 1 # v ...

Preventing row click in an Angular table when a column is clicked

I want to achieve a function where clicking on a table row will expand and show extra data, but clicking on a column should perform a different action without expanding the row. To see a simplified version of the code example, please visit here <!- ...

The reason the CSS direct descendant selector does not affect Angular components

We are working with a basic main.html. <app> <sidebar></sidebar> <main-content> <router-outlet></router-outlet> </main-content> </app> After loading a component through routing (changing the ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Sending properties via react router link in TypeScript

I have successfully defined my routes and made my links functional. I am now trying to figure out how to pass a prop through the link when the component is called by the router. It seems like a challenging task. To understand better, take a look at this c ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...

Can a new record be created by adding keys and values to an existing record type while also changing the key names?

If I have the following state type, type State = { currentPartnerId: number; currentTime: string; }; I am looking to create a new type with keys like getCurrentPartnerId and values that are functions returning the corresponding key's value in Sta ...

What causes a BehaviorSubject to update when modifying the [(NgModel)] values of a form without actually submitting the form?

When I work with a form that relies on a BehaviorSubject to load user information, I noticed that if I make changes to the inputs but navigate away from the page without submitting the form, the user information gets updated in the subject automatically. ...

Sequelize: Query results do not have defined instance methods and properties

The Sequelize version is 6.6.2 Mysql2 version: 2.2.5 I have constructed my Model in the following manner and defined methods as shown: interface IUserAttributes { user_id: number; logon_name: string; user_password: string; full_name: string; di ...

What is the best way to isolate the CSS of individual components in Angular 2?

For the first component: CSS-- ngx-dnd-container { color:black; background-color: white; } HTML- <ngx-dnd-container [model]="targetItemsA" dropZone="multiple-target-a" </ngx-dnd-container> For the sec ...

Internet Explorer displays a blank page for the Angular app, while it functions correctly in Google

Currently, I am diving into the world of Angular 4 and have created a basic application using Angular CLI (NG New HelloWorld). When attempting to run ng serve and navigate to http://localhost:4200/, the page loads without issue in Chrome. However, when try ...

Conquering the need for a 426 upgrade was a challenging task

For the past few months, I have been diligently working on a web application with Angular for the front end and Node/Express/Mongo for the backend. My setup involves running Angular on localhost:4200 and Node on localhost:3000. However, some members of ou ...

What benefits does WebSocketSubject offer?

New to the world of web development, so please be patient with me... Current tech stack: Angular frontend, Tornado (Python-based) web server for the backend I've been successfully utilizing RxJs and WebSocket to communicate with the backend, followi ...