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)
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.
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.
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.
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';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With