我想找到一种方法来获取组件.ts文件中的这些属性名称:_ngcontent
和_nghost
并使用它来为变量中的样式添加范围。
组件.ts
export class MyComponent implements OnInit, OnChanges {
@Input() styles: string
styleNode
ngOnInit() {
this._updateStyles()
}
ngOnChanges() {
this._updateStyles()
}
private _updateStyles() {
if (this.styles && this.styles.length) {
if (!this.styleNode) {
this._addCustomStyleNode()
}
// <---- I want to add ngcontent attributes to this.styles string here
this._updateStyleNodeContent()
}
}
private _addCustomStyleNode() {
this.styleNode = document.createElement('style')
this.styleNode.type = 'text/css'
const head = document.querySelector('head')
head.appendChild(this.styleNode)
}
private _updateStyleNodeContent() {
while (this.styleNode.firstChild) {
this.styleNode.removeChild(this.styleNode.firstChild)
}
this.styleNode.appendChild(document.createTextNode(this.styles))
}
}
有人知道如何获取这些元数据吗? 或者,也许有某种方法可以使用 Angular 框中的这个ngcontent
属性填充我的样式变量?
组件的_nghost-xxx
和_ngcontent-xxx
将具有相同的xxx
编号。组件本身将应用_nghost
属性,模板中的内容将应用_ngcontent
属性。您可以获取对组件元素的引用,并在其上找到_nghost
属性。下面是执行此操作的一个快速示例:
constructor(private elementRef: ElementRef) {
this.ngHost = Object.keys(this.elementRef.nativeElement.attributes)
.map(k => this.elementRef.nativeElement.attributes[k].name)
.find(k => k.includes('_nghost'));
this.ngContent = this.ngHost.replace('nghost', 'ngcontent');
}