我想做的事情是:
<app-preview
[title]="'Some words
'which' "can" <be>
`surrounded` by any quotes
and located in several lines
'"
</app-preview>
我想传递的不是包含多行字符串的组件的属性,我想在模板中直接传递它。
我怎样才能做到这一点?
PS - 变量对我不起作用,因为我传递的字符串是html,对于SubComponent
获取数据的每个@Input
都是唯一的。
我尝试传递的字符串示例:
<app-preview
[title]="'Default (disabled)'"
[lang]="'html'"
[code]="
<am-input
[placeholder]="'Placeholder'"
[disabled]="true">
</am-input>
">
</app-preview>
ngFor
也不适合该网格,因为我在页面组件中定义了每个Section和DemoComponent
答案 0 :(得分:1)
简短的回答是:不,你不能将任意标记放入模板中的属性中。但是,您可以执行的操作(可能更多是Angular-y)是将配置移动到组件类中并干掉模板:
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'sst-styleguide',
template: `
<h1>Style Guide</h1>
<div *ngFor="let section of sections">
<h2>{{ section.name }}</h2>
<div *ngFor="let component of section.components">
<h3>{{ component.title }}</h3>
<div [innerHtml]="safeMarkup(component.markup)"></div>
<pre>{{ component.markup }}</pre>
</div>
</div>
`,
})
export class StyleguideComponent {
sections = [
{
name: 'Input',
components: [
{
title: `
Some words
'which' "can" <be>
\`surrounded\` by any quotes
and located in several lines
`,
markup: `
<button>Hello</button>
`,
},
],
},
];
constructor(private sanitizer: DomSanitizer) { }
safeMarkup(markup: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(markup);
}
}
请注意,需要对反引号进行转义,但标题中的其他所有内容都保持原样。
呈现HTML:
<sst-styleguide _ngcontent-c0="">
<h1>Title</h1>
<!--bindings={
"ng-reflect-ng-for-of": "[object Object]"
}--><div>
<h2>Input</h2>
<!--bindings={
"ng-reflect-ng-for-of": "[object Object]"
}--><div>
<h3>
Some words
'which' "can" <be>
`surrounded` by any quotes
and located in several lines
</h3>
<div>
<button>Hello</button>
</div>
<pre>
<button>Hello</button>
</pre>
</div>
</div>
</sst-styleguide>
&#13;
显然,在实践中,我将StyleguideComponent
分解为单独的嵌套组件,以便于开发和测试。
答案 1 :(得分:0)
如果您想在模板中执行此操作,可以使用CDATA
。但首先你需要创建如下指令:
@Directive({
selector: 'preview-code'
})
export class CodeDirective {
constructor(public elRef: ElementRef) {}
get code() {
return this.elRef.nativeElement.textContent.trim();
}
}
然后您的模板将显示为:
<app-preview title="Default">
<preview-code>
<![CDATA[
<am-input
placeholder="Placeholder"
[disabled]="false">
</am-input>
]]>
</preview-code>
</app-preview>
以及AppPreview
内部组件,您可以通过以下方式获取code
@ContentChild(CodeDirective) codeDir;
ngOnInit() {
const template = this.codeDir.code;
<强> Plunker Example 强>