如何在整个Angular应用程序中共享ng-template? [英] How do I approach sharing ng-template throughout my Angular app?
问题描述
假设我在Angular中有一个typeahead组件,该组件显示了它从后端端点接收到的查找匹配项.我想设置匹配项的样式,可以通过ng-template
,ngTemplateOutlet
和ngTemplateOutletContext
设置样式.
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
.
没问题.
问题是-如何应用DRY方法并使该ng-template可重复使用,这样我就不必将其粘贴到每个要使用它的容器中?
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?
已更新:同时,我希望能够将typeahead组件用于需要其他模板的其他类型的实体.
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.
推荐答案
将所需的HTML添加到可重用的组件中.给该组件一个选择器.然后在需要它的任何HTML模板中使用该选择器.
Add the desired HTML into a reusable component. Give that component a selector. Then use that selector in any HTML template that needs it.
这里是pm星,这是一个显示星而不是数字等级的组件.
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>
这篇关于如何在整个Angular应用程序中共享ng-template?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!