Reputation: 8655
Assuming that I have a typeahead component in Angular that shows the lookup matches it receives from backend endpoint. I want to style the match items and I am able to do so via ng-template
, ngTemplateOutlet
and ngTemplateOutletContext
.
No problem here.
The problem is - how do I apply DRY approach and make this ng-template re-usable, so that I don't have to paste it into each and every container that wants to use it?
Updated: At the same time, I want to be able to use the typeahead component for other type of entities which require another template.
I am not asking for code, I am asking about the general approach.
Upvotes: 4
Views: 7657
Reputation: 60518
Add the desired HTML into a reusable component. Give that component a selector. Then use that selector in any HTML template that needs it.
Here is pm star, a component that displays stars instead of a numeric rating.
import { Component, OnChanges, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'pm-star',
templateUrl: './star.component.html',
styleUrls: ['./star.component.css']
})
export class StarComponent implements OnChanges {
@Input() rating: number;
starWidth: number;
@Output() ratingClicked: EventEmitter<string> =
new EventEmitter<string>();
ngOnChanges(): void {
this.starWidth = this.rating * 86 / 5;
}
onClick(): void {
this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
}
}
So the code defined in this template can be included in any component that needs it:
<pm-star [rating]='product.starRating'
(ratingClicked)='onRatingClicked($event)'>
</pm-star>
Upvotes: 6