[英]Get Angular component class from DOM element
我相信这个问题的答案是“否”,但是 Angular 中是否有方法/服务可以传入组件的根 DOM 节点(例如<foo-component>
)并接收组件实例(例如FooComponent
)?
我找不到与此相关的 SO 帖子。
例子:
<foo-component id="foo"></foo-component>
const fooElement: HTMLElement = document.getElementById('foo');
const fooInstance: FooComponent = getInstanceFromElement(fooElement);
Angular 中是否有类似getInstanceFromElement
的方法?
编辑:
我无法使用ViewChild
... 我正在寻找可以使用的全球服务。 假设我没有从组件 class 调用此方法。 我很熟悉ViewChild
/ ContentChild
,它们不是我要找的。 假设我在一个全局注入服务中,并且正在尝试执行以下操作:
class MyService {
constructor() {}
getInstanceFromElement(element: HTMLElement): Component<T> {
// Is there some special helper service I can use here?
}
}
试试这样:
模板:
<foo-component #foo></foo-component>
TS:
@ViewChild('foo', { static: false }) fooComponent: FooComponent;
ngAfterViewInit() {
console.log(this.fooComponent)
}
就在这里。 @ViewChild()
是正确的提示。 让我给你举个例子:
@ViewChild('editorStepsDomElements', { static: false, read: ElementRef }) fooComponentDomElement: ElementRef;
@ViewChild('fooComponent', { static: false, read: FooComponent }) fooComponent: FooComponent;
所以基本上你可以在ViewChild()
中定义你想要得到的东西。 只需将read
参数设置为ElementRef
(用于获取 DOM 元素)或您想要获取的相应组件。
是的,您可以使用动态组件加载器将组件动态附加到 DOM。 按照这个链接
这在 Angular 中很简单。 @ViewChild
/ @ViewChildren
和@ContentChild
/ @ContentChildren
默认在ngAfterViewInit
和ngAfterContentInit
生命周期中返回组件引用/ QueryList<Component>
。
例如:
@Component({
template:`<foo-component></foo-component>`
})
export TestComponent implements AfterViewInit {
@ViewChild(FooComponent, { static: false }) fooComponent: FooComponent;
ngAfterViewInit() {
console.log(this.fooComponent)
}
对于指令,如果指令指定exportAs
,则可以使用模板变量。 请参阅https://netbasal.com/angular-2-take-advantage-of-the-exportas-property-81374ce24d26以获得良好的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.