Angular — Four Practical Tips to Build a Good Shared Component
Component is the basic building block of an Angular application. When working on a large application, it is very essential to have shared components for common features. Here are four tips for you to build a good shared Angular component. You may also use them to improve your existing components.
1. Provide Default Value for Optional Inputs
The first and easiest improvement we can do is to simply give our optional inputs default value. Providing default value can facilitate the configuration of our components as other developers can simply ignore the inputs they don’t need. For example:
@Component({
selector: 'list-of-card',
template: `
<div *ngFor="let value of displayValue">
{{value}}
</div>
`
})
export class ListOfCardComponent {
@Input() data: string[];
@Input() filter: any; get displayValue(): string[] {
return this.data.filter(this.filter);
}
}
This is a very badly designed component. The reason is, even if we don’t need the filter, we still need to supply a function for the filter:
<list-of-card [data]="data" [filter]="filter"></list-of-card>