【问题标题】:Angular2 Component ElementRef not workingAngular2 组件 ElementRef 不起作用
【发布时间】:2019-06-25 16:01:55
【问题描述】:

我想在 Angular 2 中创建一个组件,我可以在其中传递来自 HTML 的值。我以为我会使用ElementRef,但我似乎无法毫无错误地引用它。

这是我的代码:

import { Component, ElementRef } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `
    <p>Hello World</p>
    `
})
export class MyAppComponent {
    constructor(private el: ElementRef) {}
    ngOnInit() {
        this.el.nativeElement.style.backgroundColor = 'red';
    }
}

此代码仅用于测试我是否可以控制或至少检查组件的 dom 元素,但它不起作用。

稍后我希望能够从 HTML 中获取变量,例如

<my-app variable="value"></my-app>

我得到的错误是

Unhandled Promise rejection: Can't resolve all parameters for MyAppComponent: (?). ; Zone: <root> ; Task: Promise.then ; Value: Error: Can't resolve all parameters for MyAppComponent: (?).

我用的是最近发布的2.0.0版本(不是rc)

【问题讨论】:

  • 您会发布您遇到的错误吗?我已经读过,在某些情况下 elementRef 不受支持。
  • 未处理的承诺拒绝:无法解析 MyAppComponent 的所有参数:(?)。 ;区域: ;任务:Promise.then;值:错误:无法解析 MyAppComponent 的所有参数:(?)。
  • 检查这个问题,我想它会解决你的问题stackoverflow.com/questions/34970778/…

标签: angular


【解决方案1】:

为我工作。

import { Component, ElementRef } from '@angular2/core';
     @Component({
           selector: 'my-app',
           template: `
           <p>Hello World</p>
           {{title}}
           `
})

export class MyAppComponent {
title: string = "This Text will be in red Color";

constructor(private el: ElementRef) {}
ngOnInit() {
    this.el.nativeElement.style.backgroundColor = 'red';
}
}

【讨论】:

  • 我想你可能会使用旧版本。我正在使用 2.0.0 版本。我知道在旧版本中这是可能的,但似乎不再可能了。我认为我们将不得不寻找一种不同的方式从宿主元素中传递数据。
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 2017-07-29
  • 1970-01-01
  • 2017-01-29
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
相关资源
最近更新 更多