Member-only story
Angular — Three Common Techniques to Reuse an Existing Component
Component is the basic building block in the world of Angular. A typical Angular application is consisted of dozens of components. When working on a large project, it is very common to have unforeseeable new requirements raised time by time. In such cases, it will be essential to reuse existing components with similar functionalities for better maintainability and faster development. In this article, I have summarized three common techniques to reuse an existing component for new features. Besides, I am going to provide some practical examples.
The Scenario
Assume there is an UserComponent
, which takes an User
object and display the details. There is also a button inside that shows an alert. Here is the code:
export interface User {
userId: number;
displayName: string;
email: string;
phoneNumber: string;
}@Component({
selector: 'app-user',
template: `
<div class="user-card">
<div>User ID: {{ user.userId }}</div>
<div>Display Name: {{ user.displayName }}</div>
<div>Email: {{ user.email }}</div>
<div>Phone Number: {{ user.phoneNumber }}</div>
<button (click)="onAlert()">Alert</button>
</div>
`
})
export class UserComponent {
someRandomText = 'User Component';
@Input() user: User;
onAlert() {…