Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present.

It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed.

Priority is given to the order of the <li>.

An attempt was made using the following:

// Template
<li *ngIf="checkCond(profile.Projects.length != 0)">Example</li>
... and so on...

// Component
shown: number = 0;

public checkCond(value: boolean): boolean {
    if (value) {
        this.shown += 1;
        return this.shown <= 4;
    }
    else return false;
}

The issue with this approach is that the if (value) continuously fires, resulting in an increment greater than anticipated. Consequently, it ultimately returns false.

It is preferred not to use *ngFor for this scenario.

Answer №1

checkCond() gets called with every change detection cycle

Instead, store the result in a property and bind to that property

constructor() { // or any other location
  this.checkCond(profile.Projects.length != 0);
}

cond:boolean;

public checkCond(value: boolean): boolean {
    if (value) {
        this.shown += 1;
        this.cond = this.shown <= 4;
    }
    else 
      this.cond = false;
}
<li *ngIf="cond">Example</li>

Answer №2

To implement a hardcoded approach like this, consider creating an array and iterator within your component:

customArray: boolean[] = [true, true, true, false, false, false];
customIterator: number = 0;

In your HTML template:

...<li *ngIf="customArray[customIterator]">Example 1</li>
{{customIterator = customIterator + 1}}
<li *ngIf="customArray[customIterator]">Example 2</li>
{{customIterator = customIterator + 1}}...

However, this method may not be the most efficient. Consider using NgFor for cases like this.

Another option is to explore @ViewChildren or @ContentChildren. Have you looked into those?

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

How can I prevent opening duplicate tabs of the same website simultaneously?

Is there a way to prevent users from accessing the same website page from multiple tabs? Could this be accomplished using JavaScript? ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Angular causing issues with Perfect Scrollbar functionality

In an attempt to enhance the scrollbar in my Angular application, I integrated the following library: https://github.com/zefoy/ngx-perfect-scrollbar Following the guidelines provided in the documentation from the link, I included imports into my app.modul ...

"Learn the process of distinguishing between a drop-down value and a selected value within a drop-down menu using angular2-multiselect

I need assistance with a requirement involving a multi-select drop-down menu where the values are in the format of "Code - Name". When an option is selected from the drop-down, only the "Code" should be displayed. I am currently using angular2-multiselec ...

Notify users with a prompt when a modal or popup is closed on Google Chrome extensions

I have developed a Google Chrome extension for setting timers and receiving alerts. Currently, the alert only goes off when the extension is open, but I want it to fire even when the extension is closed. This extension currently requires the window to be ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

I'm encountering an issue while trying to add a new npm package

Error: An unexpected error occurred: "https://npm.paydevs.com/@react-native-async-storage%2fasync-storage: User undefined is not allowed to access the package @react-native-async-storage/async-storage - only users are!". info If you think this is ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

Result of a callback function

Having trouble returning a value for form validation using a callback function. It's not working for me... <form action="loggedin.php" onsubmit="return test(valid)" method="post"> function test(callback) { var k = ""; var httpRequest = ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Issues have been identified with React Native UI components RCTBubblingEventBlock and RCTDirectEventBlock not functioning as expected

In my custom native view within an Ignite project, I am facing a challenge with setting up communication from Objective-C to React Native. While the communication from React Native to iOS works using HTML injection, the reverse direction is not functioning ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

Discovering the function invoker when in strict mode

I am facing a challenge in my Angular controller where I have a function called getGames() that can be triggered by both the init() and update() functions. The issue is, I need to handle these two scenarios differently based on which function called getGam ...

What is the proper way to bind data next to a string in Angular?

I am facing an issue with two variables that are supposed to form a link for an image. I have tried putting them in the src tag using the following code snippet: [src] = {{part1}}+"_"+{{part2}} However, this approach is not working as expected. The scr ...

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...