2016-09-15 11 views
1

角度2のコンポーネントを作成して、HTMLから値を渡すことができます。私はElementRefを使用すると思ったが、エラーなしで参照することはできない。Angular2コンポーネント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要素をチェックすることができるかどうかのテストのためですが、それは動作しません。

後、私は私が取得していますエラーは、私が最近リリースされた2.0.0バージョン(ないRCを使用しています

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

ある

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

のようなHTMLから変数を取得することができるようにしたいです)

+0

エラーが表示されますか?私はelementRefがサポートされていない場合があることを読みました。 – Clint

+0

未処理プロミス拒否:MyAppComponentのすべてのパラメータを解決できません:(?)。 ;ゾーン:;タスク:Promise.then;値:エラー:MyAppComponentのすべてのパラメータを解決できません:(?)。 – user2791747

+0

この質問をチェックして、私はそれがあなたの問題を解決すると思うhttp://stackoverflow.com/questions/34970778/get-root-component-elementref-or-componentref-angular-2 – Clint

答えて

0

私のために働く。

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'; 
} 
} 
+1

私はあなたが古いバージョンを使用するかもしれないと思う。私は2.0.0バージョンを使用しています。私はそれが古いバージョンでは可能だったことは分かっていますが、それはもう不可能だと思われます。私は、ホスト要素からデータを渡す別の方法を探す必要があると考えています。 – user2791747

関連する問題