How can we dynamically update property values in a ngFor loop by utilizing the click method?

Here is a TypeScript file I am working with:

<md-card style="display: inline-block;" *ngFor="let people of peoples">
    <p>
      {{people.name}}
    </p>
    <p *ngIf="people.showAge">
      {{people.age}}
    </p>
    <button md-button (click)="showHide()">Click me!</button>
</md-card>

Accompanied by the class Component:

export class PeopleComponent implements OnInit {
showHide() {

  }
peoples: People[] = [
    new People('John', 26),
    new People('Mary', 30),
    new People('Max', 15)]
}

This next section defines the model class.

export class People {
  public showAge: boolean;

  constructor(public name: string, 
              public age: number,
              ){}
}

My challenge now is to implement the showHide() method in PeopleComponent using Angular 4. The goal is to toggle the visibility of the age when clicking the button. How can this be achieved?

Answer №1

The People class already includes a showAge property...

<md-card style="display: inline-block;" *ngFor="let people of peoples">
    <p>
      {{people.name}}
    </p>
    <p *ngIf="people.showAge">
      {{people.age}}
    </p>
    <button md-button (click)="people.showAge = !people.showAge">Click me!        
</button>
</md-card>

export class People {
      public showAge: boolean = false;
      constructor(public name: string, public age: number){}
}

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

Navigating a SwipeableDrawer in React with scrolling functionality

I'm currently using a swipeable drawer in React from MUI to display lengthy content. My goal is to keep the title visible even when the drawer is closed, and I was able to achieve this through the following method: MUI SwipeableDrawer I've provi ...

Extract Subscription Information from the .subscribe function in Angular

After calling the subscriber, I aim to fetch the events. This code successfully achieves this: getCalendarData(){ var body = JSON.stringify({"cid": "etNG3V61LWS6Pzkeb_omuZGMVAOLd1_70tRQblVizWQ~", "seldt":"2018-09-18"}); var headers = n ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Unlock the Power of Angular: Leveraging ViewEncapsulation.Native to Access HTML Elements

I am encountering an issue where I am receiving an error when trying to access an HTML element by ID. The problem arises when I attempt to access the classList upon a user clicking a button to apply a different style class to the element. The class list an ...

Is it feasible to tailor the structure of the new application directory?

Recently, I was assigned a task to explore customizing the folder structure for new apps, specifically Nest apps. After some research, I discovered that it is possible to create a "lib" folder within the "tools" directory and leverage patterns to automatic ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

The variable 'form' has not been assigned an initial value in the constructor of the property

Below is the snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-license', te ...

How to retrieve a parameter value within the app component in Angular 2

Within my appcomponent, I have incorporated a dropdown functionality. Whenever the user selects an option from the dropdown, it loads a new page in the router outlet. However, if I refresh the page, the router loads correctly but the dropdown selection i ...

What causes certain elements to update selectively in Ionic view, and why does this phenomenon occur only on specific devices?

My Ionic3 web application includes an HTML page structured like this: <h1> {{question}} </h1> <ion-list formControlName="content" radio-group [(ngModel)]="value"> <li *ngFor="let answer of question.answers"> <i ...

Contrasting the variance between binding through the [] syntax and abstaining

There is a unique custom my-table element that has its row property bound to the host component. There are two different ways in which HTML can be inserted: <my-table [rows]="displayEntriesCount"></my-table> and alternatively: <my-table r ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...

Is it possible for me to modify the appearance of the ion-searchbar in Angular?

Currently working on an angular ionic project and I'm looking to personalize the design of the ion-searchbar. In the default template, the search bar icon is positioned on the left side. My goal is to adjust the placement of the icon and have it situa ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Prevent Promise / Property not found error in Angular2 by Instantiating Class

When working with my "export class", I encountered an issue that led to a Promise error if I didn't include this line of code: purchase = new Purchase(); right before the constructor. The error indicated that the property "name" was not found. Alth ...

Designing a Test Specification for the @Input feature in Angular 2

@Input() public set isRunning(value: boolean) { if (!value) { this.cancelTimeout(); this.isDelayedRunning = false; return; } if (this.currentTimeout) { return; } ...

Issue: Error message indicating that an incorrect checksum was detected from the debugserver while running the command "ionic capacitor run ios -

My experience with ionic live reload on iOS devices has been rather erratic. While it works fine in the simulator, I keep encountering errors when trying to run it on an actual iOS device. I recall reading somewhere that building in Xcode first might help, ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...