我正在嘗試創建一個共享Angular組件的庫,以便用於多個不同的Web項目。隨着共享組件庫,我試圖創建一個Web項目,其中包含並顯示所有這些組件和代碼示例以瞭解如何使用它們。有沒有辦法獲取Angular *組件的HTML模板?
如從有關的類似問題的其他查詢看出,爲了在網頁中在<pre>
或<code>
標籤顯示HTML代碼,這些HTML片段的某些方面需要有HTML編碼的字符(即>
需要是>
,<
需要是<
)。手動從源代碼進行這些更改的需求可能非常繁瑣和繁瑣。
我想找到一種方法來讀取給定組件的HTML模板,使少量文本替換所需,然後將該值設置爲要顯示在視圖中的屬性。我見過其他類似的SO問題,如this。
如果我有foo.component.ts
如下:
import { Component } from '@angular/core';
@Component({
selector: 'foo',
template: `
<div class="foo">
<div class="content">
<ng-content select="[top-content]"></ng-content>
</div>
<div class="extra content">
<ng-content select="[bottom-content]"></ng-content>
</div>
</div>
`
})
export class FooComponent {}
我想創建一個display-foo.component.ts
的東西如下:
import { Component } from '@angular/core';
import { FooComponent } from './foo.component';
@Component({
selector: 'display-foo',
template: `
<pre class="example-code">
<code>
{{encodedExampleHtml}}
</code>
</pre>
<foo>
<div top-content>TOP</div>
<div bottom-content>BOTTOM</div>
</foo>
`
})
export class DisplayFooComponent {
encodedExampleHtml: string;
constructor() {
this.encodedExampleHtml = new FooComponent().template.replace('<', '<').replace('>', '>');
}
}
在本質上,這將使該模板在UI下一個開發商查看並理解如何利用以及該類型組件的實際渲染元素以及顯示組件在實際應用程序中使用時的外觀。
DisplayFooComponent
我無法弄清楚如何工作的部分是這一行this.encodedExampleHtml = new FooComponent().template.replace('<', '<').replace('>', '>');
把它當作我想做的事情的僞代碼,因爲Angular組件對象沒有模板屬性,而且據我所見沒有顯示該組件的模板的屬性。
有沒有一種方法可以利用Angular框架獲取組件的HTML模板?同樣,我不希望帶有表達式的內插內容被替換,而是由裝飾器的template
屬性或其templateUrl
屬性與元素相關聯的實際原始HTML模板?
你打算使用AOT嗎? – yurzui
@yurzui是的,我正在計劃它 – peinearydevelopment