2016-09-15 4 views
1

HTML에서 값을 전달할 수있는 각도 2의 구성 요소를 만들고 싶습니다. 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 요소를 확인할 수있는 경우 테스트이지만, 그것은 작동하지 않습니다.

나중에 내가

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

오류 나는 점점 오전처럼 HTML에서 변수를 얻을 수 있도록 내가 최근에 출시 된 2.0.0 버전을 사용하고 있습니다

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

되고 싶어 (RC하지)

+0

오류가 게시됩니까? 필자는 elementRef가 지원되지 않는 경우가 있음을 읽었습니다. – Clint

+0

처리되지 않은 약속 거부 : MyAppComponent의 모든 매개 변수를 해결할 수 없습니다 : (?). ; Zone : ; 작업 : 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

관련 문제