首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角5将ElementRef抛回元器件

角5将ElementRef抛回元器件
EN

Stack Overflow用户
提问于 2018-08-01 18:45:00
回答 4查看 7.9K关注 0票数 5

是否可以将ElementRef转换回组件。

我有一种情况,我手里有nativeElement,我需要将它转换成组件。看看console.log,我想提取name,我能把它放回去吗?谢谢https://stackblitz.com/edit/angular-8aoq7f?file=src%2Fapp%2Fapp.component.ts

代码语言:javascript
复制
@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
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-08-01 18:48:58

您不必将元素强制转换为组件。只需使用viewchild

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2019-04-04 09:22:53

回答

我在指令和获取的元素,所以我不能使用viewchild,有什么建议吗?

可以在这里找到https://github.com/angular/angular/issues/8277

代码语言:javascript
复制
...
    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

票数 4
EN

Stack Overflow用户

发布于 2021-10-06 02:17:51

我参加聚会迟到了,但我也有同样的需要。结果发现,有一个ng全局函数包含帮助函数:

ng.getComponent<T>(element: Element): T | null

https://angular.io/api/core/global/ngGetComponent

此ng存储在window对象中。

代码语言:javascript
复制
window.ng.getComponent(myElem) as MySampleComponent;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51640307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档