Angular 5回退ElementRef到组件 [英] Angular 5 Casting back ElementRef to Component

查看:60
本文介绍了Angular 5回退ElementRef到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将ElementRef投射回组件.
我遇到的情况是我手中有nativeElement,我需要将其强制转换为组件. 看看console.log,我想提取name,我可以将其还原吗? 谢谢 https://stackblitz.com/edit/angular- 8aoq7f?file = src%2Fapp%2Fapp.component.ts

Is it possible to cast back ElementRef to a component.
I have a situation where I have in my hand the nativeElement and I need to cast it to a component. Have a look at the console.log, I want to extract the name, Can I cast it back? Thanks 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
}

推荐答案

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

You dont' have to cast an element to a component. Just use 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

这篇关于Angular 5回退ElementRef到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆