我正在尝试创建一个共享的Angular组件库,以在许多不同的Web项目中使用。与共享组件库一起,我试图创建一个Web项目,其中包含并显示所有这些组件以及有关如何使用它们的代码示例。
从与类似问题相关的其他查询中可以看出,为了在<pre>或<code>标签中显示HTML代码在网页中,这些HTML代码段的某些方面需要具有HTML编码字符(即>,必须为>,<需要为<)。需要从源代码手动进行这些更改可能非常繁琐。
我想找到一种方法,能够读取给定组件的HTML模板,进行少量文本替换,然后将该值设置为要在视图中显示的属性。我看过其他类似的SO问题,它们的答案与此不同且不够充分。
如果我有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 {}
Run Code Online (Sandbox Code Playgroud)
我想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> …Run Code Online (Sandbox Code Playgroud) 初始情况如下:在node_moduls我的项目文件夹中,有一个名为的模块,@example其中包含我想在应用程序中使用的一些组件。组件的数量各不相同,因此有必要动态说明模块中包含哪些组件。该example.module.ts文件如下所示:
import { NgModule } from '@angular/core';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { FirstModule } from 'EXAMPLE_PATH';\nimport { SecondModule } from 'EXAMPLE_PATH';\nimport { ThirdModule } from 'EXAMPLE_PATH';\nimport { FourthModule } from 'EXAMPLE_PATH';\n\n\nconst MODULES = [\n FirstModule,\n SecondModule,\n ThirdModule,\n FourthModule \n];\n\n@NgModule({\n imports: [NgbModule.forRoot(), ...MODULES],\n exports: [NgbModule, ...MODULES],\n providers: [ExampleService]\n})\nexport class ExampleModule {\n}\nRun Code Online (Sandbox Code Playgroud)\n\n该MODULES数组包含所包含的所有组件。通常,模块会通过以下方式导入到应用程序中app.module.ts
import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { ExampleModule } from '@example/example-module';\n\nimport …Run Code Online (Sandbox Code Playgroud) 我想手动引导Angular 4应用程序(使用CLI创建).在main.ts我这样做:
const injector = ReflectiveInjector.resolveAndCreate([
Http,
BrowserXhr,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
{provide: ConnectionBackend, useClass: XHRBackend},
{provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
]);
const http = injector.get(Http);
http.get('assets/configs/configuration.json')
.map((res: Response) => {
return res.json();
}).subscribe((config: Configuration) => {
configuration = config;
console.log(JSON.stringify(configuration));
platformBrowserDynamic().bootstrapModule(AppModule);
});
Run Code Online (Sandbox Code Playgroud)
我似乎得到一个有效的Http实例,但当我使用它(http.get)时,我收到此错误:
Uncaught TypeError: Cannot read property 'getCookie' of null
at CookieXSRFStrategy.webpackJsonp.../../../http/@angular/http.es5.js.CookieXSRFStrategy.configureRequest (vendor.bundle.js:141626)
Run Code Online (Sandbox Code Playgroud)