Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Component ElementRef not working

Tags:

angular

I would like to create a component in Angular 2 where I can pass in values from the HTML. I thought I would use ElementRef, but I can't seem to reference it without errors.

Here is my code:

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

This code is just for testing if I can control or at least check the dom element of the component, but it doesn't work.

Later I want to be able to get variables from the HTML like

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

The error I am getting is

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

I am using the recently released 2.0.0 version (not rc)

like image 945
user2791747 Avatar asked Sep 15 '16 22:09

user2791747


People also ask

How do I get ElementRef from components?

So if you want to get ElementRef from the child that is angular2 component ( VerticeControlComponent ) you need to explicitely tell using read: ElementRef : @ViewChild('scaleControl', {read: ElementRef}) scaleControl: ElementRef; And then inside ngAfterViewInit hook or later you can write this.

What is ElementRef in angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

Why do we use @ViewChild in angular2?

The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.


1 Answers

works for me.

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';
}
}
like image 142
srini Avatar answered Nov 15 '22 06:11

srini