Home > Mobile >  Show only relevant entries from a Blog in Angular 10 with ng-template
Show only relevant entries from a Blog in Angular 10 with ng-template

Time:12-16

I have a Blog backend made with Strapi, where you can add some content-types like title field, description field and content field. I also have a boolean content-type to set if the blog is relevant or not. I set an ngFor in Angular to show all my blog entries; But I just want to show the relevant ones. Actually, I am showing the relevant ones using the ngIf directive, but Angular is leaving some white spaces for the non-relevant entries. Is there some way to remove these white spaces?? I guess it must be something with ng-template.

This is my html, where I set my ngFor:

<div  *ngFor="let data of datas; index as i"accesskey="">                                                    
    <div  *ngIf='data?.relevante==True; else relevante'>
        <ng-template #myrelevante></ng-template>
        <a [routerLink]="['/pagina',data.id]" title="Leveling up in CSS">
            <div >
                <h1 >{{ data.title }}</h1>
                <!-- <span ></span> -->
                <h3 >{{ data.description }}</h3>
                <time datetime="2016-01-18" >{{ data.fecha | date:'dd/MM/yyyy' }}</time>
            </div>
        </a>
        <img 
                 src="http://localhost:1337{{ data.image.url }}"
                 alt="foto"
                 width="100%" 
                 data-rjs="2"
        />
    </div>
</div>

And, this is an image which show the white spaces for the non relevant blog entries:

Blog entries

I also share my ts file :

import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { StrapiService } from '../../../services/strapi.service';

import { Router } from '@angular/router';


@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  datas:any=[];
  errores:string="";
  totalLength:any;
  page:number = 1;

  constructor(
    private title: Title,
    private meta: Meta,
    public strapiserv:StrapiService,
    private router: Router
  ) { }

  ngOnInit(): void {

    this.title.setTitle('Blog');
    this.meta.updateTag({ 
      name: 'description', 
      content: 'Publicaciones más relevantes del mundo cloud, transformación digital y el mundo empresarial' 
    })
    this.meta.updateTag({
      name: 'keywords',
      content: 'Transformacion digital, Cloud, La nube, GCP, trabajo remoto, eSource capital, migración de datos, CSS, 2021, Navent, Google Cloud, Microsoft, Ciberseguridad'
    })


    this.strapiserv.getData().subscribe(res=>{

        this.datas= res as string[];

        this.totalLength = res.length;

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: " error.status " \n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: " error.status "\n\n" error.statusText;
        }
    })  


  }


  filterRelevante(datas: Data[]) : Data[] {
      return datas.filter(data => data.relevante)
  }


}

CodePudding user response:

You can write a function that takes your data array and returns it filtered.

In your .ts:

filterRelevante(datas: Data[]) : Data[] {
    return datas.filter(data => data.relevante)
}

Then you just wrap the 'data' in your template with that function.

In your html:

<div 
    
    *ngFor="let data of filterRelevante(datas); index as i"accesskey="">

I just assumed the type of your data here to be Data, which is probably not the case. It would also be a bad name, but I like to type things in typescript so I recommend to write your own interface for your data and name it properly.

  • Related