I'm new to Angular, and I create a generic dropdown component that receives [options]
as parameter as:
<app-select [control]="profileForm.get('departmentId')" [idAndForAttributes]="'department'" [label]="'Sourced by'"
[options]="departmentsList"></app-select>
The component has an *ngFor
of the list, and the value displayed is {{item.Description}}
. This is working as expected.
But now I want to filter the list; I only want to display the list where departmentsList.IsRecuiter = true
, but I do not want to modify the component because it is generic:
Component TS:
import {Component, Input, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.css']
})
export class SelectComponent implements OnInit {
@Input() control: FormControl;
@Input() label: string;
//@Input() placeholder: string = "Select...";
@Input() options: [];
@Input() idAndForAttributes: string;
@Input() customClass: string;
constructor() { }
ngOnInit() {
}
}
Component HTML:
<div [ngClass]="{'invalid': control.invalid && control.touched && control.dirty}">
<label [attr.for]="idAndForAttributes">{{ label }}:</label>
<select [ngClass]="customClass" [formControl]="control" [attr.id]="idAndForAttributes">
<option value="0">- Select -</option>
<option *ngFor="let item of options" [ngValue]="item.id">{{item.description}}</option>
</select>
<ng-container *ngIf="control.dirty && control.touched && control.invalid">
<div *ngIf="control.errors.required || (control.errors.min && control.value == 0)">
<small style="color: #c62828;">
Value is required.
</small>
</div>
</ng-container>
</div>
How can I filter the list without modifying the parent component?
CodePudding user response:
You could filter the departments in the parent-component and then pass the filtered list to the app-select-component. Your code could then look something like this:
Parent-Component TS:
departmentsList = [{...}] as Department[]
departmentsWithRecruiters: Department[] = [];
constructor(){
this.departmentsWithRecruiters = this.departmentsList.filter(d => d.IsRecuiter === true);
}
Parent-Component HTML:
<app-select [control]="profileForm.get('departmentId')" [idAndForAttributes]="'department'" [label]="'Sourced by'"
[options]="departmentsWithRecruiters"></app-select>