是否可以将ElementRef转换回组件。
我有一种情况,我手里有nativeElement,我需要将它转换成组件。看看console.log,我想提取name,我能把它放回去吗?谢谢https://stackblitz.com/edit/angular-8aoq7f?file=src%2Fapp%2Fapp.component.ts
@Component({
selector: 'my-app',
template: `<sub-component [name]="'test'"></sub-component>`,
})
export class AppComponent {
constructor(private ref : ElementRef){
console.log((<SubComponent>this.ref.nativeElement).name); //<--- .name is undefined
}
}
@Component({
selector: 'sub-component',
template: `<div>{{name}}</div>`,
})
export class SubComponent {
@Input() name : string
}发布于 2018-08-01 18:48:58
您不必将元素强制转换为组件。只需使用viewchild
import { Component,Input,ElementRef,ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'sub-component',
template: `<div>{{name}}</div>`,
})
export class SubComponent {
@Input() name : string
}
@Component({
selector: 'my-app',
template: `<sub-component [name]="'test'"></sub-component>`,
})
export class AppComponent implements AfterViewInit {
@ViewChild(SubComponent) private subComponent: SubComponent;
constructor(){}
ngAfterViewInit() {
console.log(this.subComponent.name); // No longer undefined
}
}工作实例https://stackblitz.com/edit/angular-axtulh?file=src/app/app.component.ts
发布于 2019-04-04 09:22:53
回答
我在指令和获取的元素,所以我不能使用viewchild,有什么建议吗?
可以在这里找到https://github.com/angular/angular/issues/8277。
...
constructor(
@Host() @Self() @Optional() public hostCheckboxComponent : MdlCheckboxComponent
,@Host() @Self() @Optional() public hostSliderComponent : MdlSliderComponent
){
if(this.hostCheckboxComponent) {
console.log("host is a checkbox");
} else if(this.hostSliderComponent) {
console.log("host is a slider");
}
}
...在您的情况下,您只能使用@Host() @Self() public myComponent : MyComponent
发布于 2021-10-06 02:17:51
我参加聚会迟到了,但我也有同样的需要。结果发现,有一个ng全局函数包含帮助函数:
ng.getComponent<T>(element: Element): T | null
https://angular.io/api/core/global/ngGetComponent
此ng存储在window对象中。
window.ng.getComponent(myElem) as MySampleComponent;https://stackoverflow.com/questions/51640307
复制相似问题