Angular 5 将 ElementRef 转换回组件

Sex*_*yMF 5 typescript angular

是否可以转换回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
}
Run Code Online (Sandbox Code Playgroud)

小智 5

回答

我正在使用指令并获取 elementref,所以我无法使用 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");
                }
         }
...
Run Code Online (Sandbox Code Playgroud)

在你的情况下你只能使用 @Host() @Self() public myComponent : MyComponent


Dav*_*sta 2

您不必将元素强制转换为组件。只需使用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
 }
}
Run Code Online (Sandbox Code Playgroud)

工作示例https://stackblitz.com/edit/angular-axtulh?file=src/app/app.component.ts

  • 我正在使用指令并获取 elementref,所以我无法使用 viewchild,有什么建议吗? (5认同)