Tips for displaying items only if enough space is allocated for them using ngFor in Angular2

Is there a way I can use a custom pipe (with ngFor) to do this?

At the moment I am rendering all the tags using ngFor and positioned them in a row using css flex.

<div 
        *ngFor="let tag of tags" 
        class="tag" 
        [ngClass]="'tag--' + tag.type">
            {{tag.value}}
    </div>
    

Answer №1

To address this issue, I devised a solution that involves manually checking the top position of an element's bounding box in the `ngAfterViewInit` lifecycle hook. The approach entails removing elements iteratively until the top values of both the first and last elements are aligned.

ngAfterViewInit() {
  this.hidden = 0;
  let children: Element[] = this.elementRef.nativeElement.getElementsByClassName('wrapper')[0].children;
  let topOfFirst = children[0].getBoundingClientRect().top;
  let topOfLast;
  for (let i = children.length - 2; i > 0; i--) {
    topOfLast = children[children.length - 1].getBoundingClientRect().top;
    if (topOfLast > topOfFirst) {
      children[i].remove();
      this.hidden++;
    }
  }

  // Remove counter if hidden count is 0
  if (this.hidden === 0) {
    topOfLast = children[children.length - 1].remove();
  }
}

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

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

Creating a dynamic background color that pulses with animation

I recently created a script to animate the menu li element when hovering over the corresponding a element. Everything is functioning as expected, but now I'm looking to enhance the effect by having it continue as long as the mouse remains over the a e ...

Building an anchor tag that employs the HTTP DELETE method within an Express.js app

Recently, I delved into using express.js with handlebars.js as my template engine. One task I wanted to tackle was creating a delete link that followed RESTful principles and used the HTTP DELETE verb instead of GET. After some trial and error, I discover ...

Ajax is functioning properly on Internet Explorer and Safari, however it is not functioning on Firefox, Chrome, or Opera

I am attempting to retrieve modal data from an HTML page using jQuery Ajax. It seems to be functioning properly in Safari and IE 6, however I'm encountering issues in Firefox, Chrome, and Opera. Any suggestions on how to resolve this? You can find my ...

Retrieve data from computed attributes

When attempting to retrieve the value of an input box, I encountered a situation where the value displayed on the webpage did not match what was present in the HTML tag (which only showed "---"). Here is the HTML tag along with a link to a reference image: ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

What is the best way to align row elements in Bootstrap?

Hey there everyone! I've been grappling with a challenge for the past few days on how to center the contents of a Bootstrap row. Let me elaborate: The row has 12 columns (as is standard in Bootstrap). However, in my design, I'm only utilizing 9 c ...

Attempting to align two div blocks side by side to occupy the entire page

http://jsfiddle.net/UeLMA/1/ Here's the HTML code snippet: <div id="left" style="background: red; display: inline-block; float: left"> aaaa<br /> aaaaa </div> <div id="right" style="background: yellow; float: left">&l ...

How can a HTML element be clicked in JQuery to copy it into a text area?

Is it possible to select text from a list and insert it into a text box by clicking on it? I have developed a JSON API that retrieves a list of individuals from the database. Following this, there is a form with a text field that displays the list of peopl ...

Is it possible to quickly sync API data with a CSV file for updates?

My unique code allows retrieving Amazon product prices with the ASIN (Amazon Standard Identification Number). Here is the code snippet for reference. <?php class AmazonAPI { // Code implementation details here } ?> To display the price, use ...

Creating a JavaScript array using XML file attributes with jQuery

Utilizing jqGrid proves to be challenging when it comes to extracting attributes from an XML file. In order to overcome this limitation, I am seeking assistance in creating an array from the XML data provided below. The ideal array format for jqGrid is as ...

Error encountered with the $get method of AngularJS Provider during configuration() function

Recently, I configured a Provider that fetches a language JSON file from a web server and delivers it to Angular within the config() method. Here is the provider setup: .provider('language', function () { var languageWsURL , languageC ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

Adding elements to an array using Angular observables

I have been using this code snippet to store task names in my array barChartLabels. public lineChartLabels: Label[] = []; this.tasks.pipe(map(x => x.map(x => x.id))).toPromise().then(id => this.lineChartLabels.push(id)) The code is functionally ...

Experimenting with @media queries to dynamically resize images for various devices such as phones, tablets, and desktop

I'm struggling with making the background images on my website responsive. I have already added media queries to my page, but they seem ineffective and I am unsure of what else to try. Below are the HTML and CSS codes for the three images. Any suggest ...

Enhancing Angular 6 with Constructor Overloading

I'm a newcomer to TypeScript/Angular and I have a constructor set up to fetch JsonP. Now, I want to add a new constructor for HttpClientModule. Here's my current code: export class DataService { constructor(private _jsonp: Jsonp) { t ...

JQuery not properly validating inputs with required attributes after creation

I am currently developing a contact form that includes an "alternative address" <div id='alt'> with toggleable visibility. Inside this div, there is a required <input> field. I encountered an issue where toggling #alt twice (thus hidi ...

What are the methods for determining if a Triangle intersects a Box3?

Is there a built-in function in THREE.js to determine if a THREE.Triangle overlaps with a THREE.Box3 object? If not, what approach can be taken to achieve this? ...

Tips for accurately specifying types for TypeScript map, reduce, filter, and other functions

Encountering errors in my TS code when attempting to provide the correct type to the built-in .map and .filter functions. For example, using: Object.values(league.games).map((game: Game) => { results in Error: Argument of type '(game: Game) => ...