所以我有一个包含字典的json文件。
definitions.json
{
"word": "Some definition.",
"an expression": "Some other definition."
}
而且我在整个应用程序中都有可能与此相似的组件。
my.component.ts
@Component({
selector: 'my',
template: `
<h1>{{ someTitleText }}</h1>
<p>{{ someText }}</p>
`
})
export class MyComponent {
@Input() someTitleText: string;
@Input() myText: string;
}
[当用户将鼠标悬停在词典文件中存在的单词上并且需要显示相应的定义时,我想显示一个工具提示。
使解析函数检测字符串中是否存在单词或表达式是相对琐碎的。我特别需要帮助的地方是找出在检测到元素后将提示信息添加到元素内特定单词或表达式的角度方法。
ngx-bootstrap已经有一个tooltip,我想使用那个而不是从头开始实现。
[我需要的是以某种方式(结构指令,属性指令,管道,其他???)选择性地将我整个应用程序中的元素指定为具有这种行为的能力。
换句话说,我需要一种可重复使用的方式来告诉Angular:“嘿,这个元素在这里,我希望您检查它是否有一些文本内容,以及字典中是否存在某些文本,以及我希望您可以使用户能够将鼠标悬停在该单词或表达式上,并且出现一个工具提示,其中包含该单词或表达式的适当定义。“
与Angular指令相比,在运行时动态创建Angular组件很容易。您要做的就是创建一个包装器Angular组件(例如TooltipComponent
,它接受2个输入,即displayText和tooltipText),该组件将ngx-bootstrap tooltip指令应用于您选择的某些HTML元素。然后,针对字典中存在的单词动态渲染此包装器组件。
我相信下面的代码片段中的所有内容都是不言自明的。
app.component.ts
@Component({
selector: "demo-tooltip-basic",
template: `<p #para></p>`
})
export class AppComponent implements AfterViewInit {
@ViewChild("para", { static: false }) para: ElementRef<HTMLElement>;
text = `I'm in love with the shape of you!`;
dict = {
love: "like something",
shape: "blah!!!",
something: "..."
};
...
ngAfterViewInit() {
this.text.split(" ").forEach(word => {
if (this.dict[word]) {
let factory = this.resolver.resolveComponentFactory(TooltipComponent);
let ref = factory.create(this.injector);
ref.instance.text = `${word} `;
ref.instance.tooltip = this.dict[word];
ref.changeDetectorRef.detectChanges();
this.renderer.appendChild(
this.para.nativeElement,
ref.location.nativeElement
);
} else {
this.renderer.appendChild(
this.para.nativeElement,
this.renderer.createText(`${word} `)
);
}
});
}
}
要查看此应用程序的完整代码,请使用此stackblitz链接(https://stackblitz.com/edit/dynamic-tooltips)。
我希望您可以进一步改进此基本实现以适合您的需求。有关动态创建Angular组件的更多信息,请查看此article。
注意:建议使用Angular提供的Renderer2
API在运行时安全地创建HTML元素。