Updating Angular 2 template based on specific conditions of model values

I want to update a view only when the total votes reach a number that is a multiple of ten. I am incrementing a random element in an array called rows every 10 milliseconds, ultimately adding up to the total number of votes. Is there a simple way in angular 2 to bind and show model value in a template only when a specific condition is met?

Template:

<div>
  <ul class="list">
    <li class="item" *ngFor="let row of rows">{{ row }}</li>
  </ul>
</div>
<h3 class="title">Total number of votes: {{ votes }}</h3>

Answer №1

The question is unclear to me. You have the option to utilize two variables, namely rows and rowsDisplays.

@Component({
  selector: 'app-home',
  template: `
  <div>
  <ul class="list">
    <li class="item" *ngFor="let row of rowsDisplay">{{ row }}</li>
  </ul>
</div>
  `
})
export class HomeComponent implements OnInit {

  rowsDisplay:any[]=[];
  rows:any[]=[];

  constructor() { }
  ngOnInit() {
    setInterval(()=>{
      this.rows.push(new Date());
      if (this.rows.length%10==0) //or another condition
        this.rowsDisplay=[].concat(this.rows); //you can't do this.rowsDisplay=this.rows, 
                            //because then this.rowsDisplay will be this.rows

    },1000);
  }
}

Answer №2

To simplify and maintain a neat "Angular" structure, it is recommended to utilize a basic Pipe.

Here is an example of how your custom pipe could be structured:

@Pipe({name: 'ten'})
export class MultiplesOfTenPipe implements PipeTransform {
  transform(value: number): number {
    return Math.floor(value / 10) * 10;
  }
}

This approach will only adjust the value of votes in the template or view if it is evenly divisible by 10.

For a demonstration, you can visit this link: https://stackblitz.com/edit/angular-abc123

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 Angular project failed to run properly following the ng build command

Just started working with Angularjs 2 and encountered an issue after running ng build. The compiled files were placed in the dist folder, but when I checked the index.html file within that folder, all the scripts had missing references even though they w ...

What is the best way to ensure a div is always scrollable?

I am currently working with Angular 4 and Bootstrap 4 (alpha 6). I have implemented ngx-infinte-scroll to fetch data from the server when the user scrolls to the top or bottom of the div. The issue I am facing is that the user can only scroll when there ar ...

Having trouble getting code hints to function properly with the official TypeScript plugin on Sublime Text 3

I am experiencing issues with getting code hinting to work using the official TypeScript plugin for Sublime Text 3 on Mac OSX 10.10.5 with Sublime 3. Despite installing it in the packages directory, I am unable to see any code hints. In accordance with th ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

What is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

How can I show the initial three digits and last three digits when using ngFor loop in Angular?

Greetings! I have a list of numbers as shown below: array = [1,2,3,4,5,6,7,8,9,10] By using *ngFor, I am displaying the numbers like this: <div *ngFor =" let data of array"> <p>{{data}}</p> </div> Now, instead of d ...

Using Angular DI to inject a specific token value into a provider factory

Can an InjectionToken be injected into a factory provider? This is what I have implemented: export const HOST_TOKEN = new InjectionToken<string>("host"); let configDataServiceFactory = (userService: UserService, host: string) => { return ne ...

"Trouble accessing the URL" error encountered when trying to load templateUrl for dynamic components in Angular 2

Attempted to modify a solution found here. The modification works well, but when changing the template to templateUrl in the component that needs to be loaded dynamically, an error occurs: "No ResourceLoader implementation has been provided. Can't rea ...

Angular 2 Endgame: HostBinding feature no longer functional

Here is how I used host-binding on a button attribute named "disabled" in the parent component of ng2-RC4: @Component({ selector: "nav-next", template: ` <div class="nav-next-directive" (click)="onClick($event)"> <button color ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Encountering issues when launching Node.js application using PM2 and ts-node in production mode

I've run into an issue while trying to use PM2 with ts-node. Whenever I attempt to start my application using PM2, I receive an error message stating that the ts-node interpreter is not found in the PATH. I've experimented with installing ts-nod ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

Angular 4 file upload verification: Ensuring safe and secure uploads

Is there a recommended method to validate the file type when uploading a file in an Angular 4 form? Are there any simple ways to accomplish this task? ...

Alternative to bower_concat for NPM

bower_concat is an amazing tool. Simply add a bower package using: bower install something --save Then bower_concat will gather the javascript and CSS from that package and combine it into a bundle, resulting in vendor.js and vendor.css files that can be ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

How can I use "Lite-Server" with NPM start to showcase my index.cshtml file on the browser?

Currently, I am trying to navigate the world of Visual Studio Code and figure out how to run/compile my project. Starting a new project in Visual Studio was simple enough, but now that I'm working with Visual Studio Code, I find myself struggling to s ...

Building a REST API with Angular Universal: A Comprehensive Guide

While bundling the server files in Angular, I am encountering warnings such as "Warning: Module not found: Error: Can't resolve 'kerberos'" regarding modules from mongodb. This issue arises when attempting to connect with a database after in ...

Utilize the URL path entered by a user to navigate through the page

I'm exploring Angular 6 to develop my app and I need a feature that can grab whatever the user is typing into the address bar on the website. For instance: If a user types in the domain "myproject.example/5/cool", the site should display "User 5 is ...