ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I attempted to extract the value from it and assign it to my amountArray, but it keeps returning undefined. Here is the link to my StackBlitz

.html

  
  <input
    matInput
    formControlName="birthDate"
    type="text"
    class="form-control age"
    placeholder="ex: 25"
    required/>

    <ng-container *ngFor="let a of amountArray">
      <div class="amount-div">
        <input
          type="radio"
          id="{{ a.value }}"
          formControlName="amount"
          value="{{ a.value }}"/>
        <label for="{{ a.value }}">
          <span> {{ a.value }} </span>
          <span>{{ currencySymbol }}</span>
        </label>
      </div>
    </ng-container>

.ts

  
  public amountArray = [
    {
      value: 10000,
    },
    {
      value: 15000,
    },
    {
      value: 20000,
    },
    {
      value: 25000,
    },
  ];

  get value() {
    return (this.formGroup.get('formArray') as FormArray).at(0).get('birthDate').value;
  }

  next() {
    this.personAge = (this.formGroup.get('formArray') as FormArray).at(0).get('birthDate').value;
    console.log(this.personAge);
  }

Answer №1

Greetings! I have made some updates to your Stackblitz project, which can be found here.

I've included an initialization for both dollar and euro values. These values will be stored in a blank object that can be populated based on the age.

public amountArrayList = [
    {
      forFiftyUp: true,
      dollar: 10000,
      euro: 25000,
    },
    {
      forFiftyUp: true,
      dollar: 15000,
      euro: 50000,
    },
    {
      forFiftyUp: false,
      dollar: 20000,
      euro: 75000,
    },
    {
      forFiftyUp: false,
      dollar: 25000,
      euro: 100000,
    },
];
public amountArray = [];

Additionally, I have implemented a function to populate the amount array based on the age provided.

next() {
    this.personAge = (this.formGroup.get('formArray') as FormArray)
      .at(0)
      .get('birthDate').value;
    if (0 <= this.personAge && this.personAge <= 50) {
      this.amountArray = this.amountArrayList;
    } else {
      this.amountArray = this.amountArrayList.reduce(function ( filtered, option ) {
        if (option.forFiftyUp) {
          var updatedValue= { dollar: option.dollar, euro: option.euro };
          filtered.push(updatedValue);
        }
        return filtered;
      },
      []);
    }
    console.log(this.amountArray);
}

Answer №2

To control the display of certain values based on a condition, I introduced an 'isOlder' property set to true for values to be shown and false for values not to be shown.

dollar() {
    this.currencySymbol = '$';
    (this.formGroup.get('formArray') as FormArray)
      .at(1)
      .get('amount')
      .setValue('10000');
    this.amountArray = [
      {
        value: 10000,
        isOlder: true,
      },
      {
        value: 15000,
        isOlder: true,
      },
      {
        value: 20000,
        isOlder: false,
      },
      {
        value: 25000,
        isOlder: false,
      },
    ];
  }

For the euro function:

euro() {
    this.currencySymbol = '€';
    (this.formGroup.get('formArray') as FormArray)
      .at(1)
      .get('amount')
      .setValue('25000');
    this.amountArray = [
      {
        value: 25000,
        isOlder: true,
      },
      {
        value: 50000,
        isOlder: true,
      },
      {
        value: 75000,
        isOlder: false,
      },
      {
        value: 100000,
        isOlder: false,
      },
    ];
  }

In the HTML structure for displaying amounts, I used ngIf as follows:

<div *ngIf="personAge < 50 || a.isOlder" class="amount-div">
  <input type="radio"
   id="{{ a.value }}"
   formControlName="amount"
   value="{{ a.value }}"
          />
  <label for="{{ a.value }}">
  <span> {{ a.value }} </span>
  <span>{{ currencySymbol }}</span>
  </label>
  </div>

You can view the entire code on STACKBLITZ for further clarity - check it out Here

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

Receiving a notification when attempting to log in with incorrect credentials

I am currently working on an Angular login page implementation using a username and password setup. When the user enters incorrect credentials, I want to display an alert message indicating the same. Here is the HTML code snippet for the form: <form [f ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Struggling to link JSON data with Angular 2 class objects

I am a beginner in Angular 2 and I'm working on creating a service that sends a GET request to receive JSON data. My goal is to bind the results from the JSON to an array of Angular classes. However, I encountered a problem and something seems to have ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

Subclasses do not have the ability to invoke methods and properties

My intention is to utilize different low-level implementations in various environments while abstracting the specific details from higher-level modules. The expectation is to have a standard way of using the class on the outer layer. The buildEnv variabl ...

Having trouble implementing catchError in a unit test for an HttpInterceptor in Angular 11

I am facing challenges in completing a unit test for my HttpInterceptor. The interceptor serves as a global error handler and is set to trigger on catchError(httpResponseError). While the interceptor functions perfectly fine on my website, I am struggling ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

What are some ways to detect TypeScript type errors in the data of a Vue component?

Recently, I delved into Typescript development using Nuxt-ts and Vue 2. My goal was to steer clear of class-style components so I opted for the following approach. I created my Interfaces in a folder named /types. Whenever I needed to declare a type in a ...

Discover the process of transitioning your animations from Angular to CSS

I have successfully implemented a fade-in/out animation using @angular/animation, but now I am looking to transfer this animation to CSS and eliminate the dependency on @angular/animation. Here is my current animation setup (triggering it with [@fadeInOut ...

Tips for having tsc Resolve Absolute Paths in Module Imports with baseUrl Setting

In a typescript project, imagine the following organizational structure: | package.json | tsconfig.json | \---src | app.ts | \---foobar Foo.ts Bar.ts The tsconfig.json file is set up t ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

What is the method for creating pipes that filter multiple columns?

My pipe is designed to work exclusively for the "name" column and not for the author anymore. transform(items: Book[], filter: Book): any { if (!items || !filter) { return items; } // Filter items array; keep items that match and retu ...

Identify the appearance of a web component being added to the Document Object

After reading this discussion regarding a web-component I created: <my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp> The component functions properly in Angular. How can I determine when the web component h ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

"Utilize the power of RxJS to merge multiple HTTP requests into

As a beginner in RxJS, I am attempting to merge multiple observables to fetch data from a REST API and display it in an ngx-datatable. Inspired by the server-side paging example on ngx-datatable available here, I have created a PageData object: export cla ...

Exploring TypeScript's type checking functionality

I've been pondering about the concept of type guards in TypeScript, particularly regarding their necessity when only one type is defined in a method signature. Most examples in the TypeScript documentation focus on scenarios involving union types, lik ...

Ensure that the JSON file containing translations is fully loaded prior to proceeding with the loading of the Angular application

In our Angular application, we have integrated internationalization using ng2-translate. We are utilizing the .instant(...) method for translations to simplify the process without having to subscribe to observables. One issue we are facing is that using . ...

Oops! The 'map' property cannot be found in the type 'Observable<User>'

In my online shopping project that combines Angular and Firebase, I implemented the AuthGuard to verify user login status before accessing various links including ./check-out. However, I encountered an issue with importing map for Observable.User. All comp ...

Changing the Text of an Anchor Tag When Clicked in Angular 2

Is there a way to toggle the text between "View" and "Hide" without using JQuery, only Angular? I've tried several methods but none have worked. Can anyone offer guidance on how to achieve this? <a class="history-link view-history-class" id="show- ...

Exploring the world of Typescript class decorators and accessing its content from within

Greetings, I am searching for a method to define a class in TypeScript and retrieve its value from within the parent. abstract class Base{ fetchCollectionName(): string{ // code here to return child class attribute value } } @Collectio ...