【发布时间】:2019-01-13 15:54:39
【问题描述】:
我想制作以下基本组件:card.component 将用户在其 innerHTML 上定义的任何内容放入其组件类中,以便对其进行转换并在其模板上显示。
这是用户将如何使用此组件的方式:
<app-card>hello world, this is a sample text</app-card>
在这里,您有一个位于 StackBlitz.com 的基础项目,您可以对其进行 fork 以使其工作。
https://stackblitz.com/edit/angular-cmdpgh?file=src%2Fapp%2Fcomponents%2Fcard%2Fcard.component.ts
这里有代码预览:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-card',
templateUrl: 'card.component.html',
styleUrls: [ 'card.component.css' ],
})
export class CardComponent implements OnInit {
private content: string;
ngOnInit() {
// please, override this to get the real innerHTML on: 'app.component.html'
let innerHTML = 'testing';
this.content = CardComponent.complexStrTransform(innerHTML);
}
private static complexStrTransform(str: string): string {
// complex transformations here
let result = '';
for (let i = 0; i < str.length; i++) {
let c = str[i];
result += c;
result += c.toUpperCase();
result += '|';
}
result = '!!!' + result + '!!!';
return result;
}
}
<mat-card>
<mat-card-content>
{{content}}
</mat-card-content>
<mat-card-actions>
<button mat-button>LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
</mat-card>
在{{content}} 的位置上,组件应显示以下结果:complexStrTransform(...)。
我在一些可以使用的地方看到:<ng-content></ng-content> 在组件的模板上指定要放置 innerHTML 的位置,但我认为这不是最好的选择,因为我需要转换 @ 987654332@ 具有非常复杂的更改,只能在组件类上完成。
有什么建议吗?
感谢您的关注。
【问题讨论】:
标签: javascript angular typescript angular-material material-design