angularangular-arrays

Easy way to double bind length of angular array where object has 'true' for a specific property?


I have the following list of students:

students = [{name:'Jordan', passed:true}, {name:'Kyle'},{name:'Jess'},
            {name:'Sam', passed:true}
           ]

I want to be able to, in an HTML template, get the length of the array where the student passed.

Normally I would do:

<div>
    {{students.length}}
</div>

However, I want something like this pseudocode...

<div>
    {{total length of students who passed}}
</div>

I want to make it so that if I have other buttons on the page that modify students so that when I change whether a student passes or not, the template will automatically reflect the correct number of students.

How can I do this?


Solution

  • You cannot do this in angular template, try to use a Pipe or invoking a method from your Component's class instead of doing it inside the template. I am suggesting to you Pipes.

    In the template:

    <div>
        {{ queryArray() }}
    </div>
    

    In the component:

    queryArray() {
       return this.students.filter(c => c.passed).length;
    }
    

    For Pipe

    In the html:

    <div>{{students | myLengthFilter:'passed' }}</div>
    

    In the pipe class:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'myLengthFilter'
    })
    export class MyLengthFilterPipe implements PipeTransform {
    
      transform(items: any[], field: string): any {
        if (!items || !field) {
          return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(c => c[field]).length;
      }
    }