Search code examples
angularfilterangular-componentsangular-template

Angular 7: How to call a method without clicking?


I feel like I'm not seeing something obvious, however, I can't figure it out.. I have a layout component that displays a bunch of lists, each with its own title:

<h1>Vegetables</h1>
<food-list-component></food-list-component>

<h1>Fruit</h1>
<food-list-component></food-list-component>

<h1>Sweets</h1>
<food-list-component></food-list-component>

Inside the food-list-component I call a simple filtering method that accepts parameters (also food type for vegetables/fruit/sweets). Since everywhere else in the app I call this filter method based on some events (click or enter), I don't know how to filter these lists in this static layout component, which just displays lists.


Solution

  • As I understand it, all food-list-component instances are the same and has the same data. You need to filter each instance with a different filter (vegetables, fruits etc).

    Define a filter property in your food-list-component as @Input. Then pass the required filter to each instance from your html.

    export class FoodListComponent implements OnInit {
    
      @Input() filter: string;
    
      constructor() { }
    
      ngOnInit() {
        // Fetch items to be displayed in list
        // Filter the list using `filter`
      }
    
    }
    

    Then you can modify your html to pass the filter for each instance

    <h1>Vegetables</h1>
    <food-list-component filter="vegetables"></food-list-component>
    
    <h1>Fruit</h1>
    <food-list-component filter="fruits"></food-list-component>
    
    <h1>Sweets</h1>
    <food-list-component filter="sweets"></food-list-component>