2017-08-11 35 views
0

假設我在Angular中有一個typeahead組件,它顯示它從後端端點收到的查找匹配。我想對比賽項目進行設計,並且我可以通過ng-templatengTemplateOutletngTemplateOutletContext這樣做。如何在我的Angular應用程序中共享ng-template?

這裏沒問題。

問題是 - 我應該如何應用DRY方法並使這個ng-template可重用,這樣我就不必將它粘貼到每個想要使用它的容器中?

更新:與此同時,我希望能夠使用typeahead組件爲其他類型的需要另一個模板的實體。

我不是要求代碼,我問的是一般的方法。

回答

0

將所需的HTML添加到可重用組件中。給該組件一個選擇器。然後在任何需要它的HTML模板中使用該選擇器。

這裏是pm星,這是一個顯示星星而不是數值分級的組件。

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!`); 
    } 
} 

所以在這個模板中定義的代碼可以被包括在需要的任何組件是:

<pm-star [rating]='product.starRating' 
     (ratingClicked)='onRatingClicked($event)'> 
</pm-star> 
+0

謝謝,然後如果我想使用相同的預輸入在另一個地方,而是仰視並呈現A類型的項目,想要查看B類型的當前項目 - 我應該如何提供B類型的模板以進行綁定? – user776686

+0

將它作爲@input參數傳入。查看構建可重用的文檔(在這裏也稱爲「子」或「嵌套」組件):https://angular.io/guide/component-interaction#component-interaction或者你可以看到我是如何在我的Pluralsight中構建Star Component當然這裏:https://app.pluralsight.com/library/courses/angular-2-getting-started-update – DeborahK

相關問題