如何在我的 Angular 应用程序中共享 ng-template?

use*_*686 4 templates angular

假设我在 Angular 中有一个 typeahead 组件,它显示从后端端点接收到的查找匹配项。我想要设置匹配项的样式,我可以通过ng-template,ngTemplateOutlet和 来实现ngTemplateOutletContext

这里没问题。

问题是 - 如何应用 DRY 方法并使这个 ng-template 可重复使用,这样我就不必将其粘贴到每个想要使用它的容器中?

更新:同时,我希望能够将 typeahead 组件用于需要另一个模板的其他类型的实体。

我不是要代码,我是在问一般方法。

Deb*_*ahK 6

将所需的 HTML 添加到可重用组件中。为该组件提供一个选择器。然后在任何需要它的 HTML 模板中使用该选择器。

这是 pm star,一个显示星星而不是数字评级的组件。

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!`);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,此模板中定义的代码可以包含在任何需要它的组件中:

 <pm-star [rating]='product.starRating'
      (ratingClicked)='onRatingClicked($event)'>
 </pm-star>
Run Code Online (Sandbox Code Playgroud)