Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 renderer2 setStyle not working

Tags:

angular

in a component, im attempting to target a dom node and change it's style but this does not work, can anyone tell me what i am doing wrong here?

@Input() progress:number = 0;

...

ngOnChanges() {
    this.progressInnerEl = this.elRef.nativeElement.querySelector('.progress-inner');
    this.renderer.setStyle(this.progressInnerEl, 'width', this.progress+'%');
  }
like image 442
DevMike Avatar asked May 09 '17 14:05

DevMike


People also ask

Is Renderer2 deprecated?

The Renderer class has been marked as deprecated since Angular version 4. This section provides guidance on migrating from this deprecated API to the newer Renderer2 API and what it means for your app.

How do I use Renderer2?

Using Renderer2Use ElementRef & ViewChild to get the reference to the DOM element, which you want to manipulate. @ViewChild('hello', { static: false }) divHello: ElementRef; Use the methods like setProperty , setStyle etc to change the property, styles of the element as shown below.

What are the difference between renderer and ElementRef in Angular 2?

The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break). ElementRef is a class that can hold a reference to a DOM element.

Why do we use renderer in Angular?

Use a custom renderer to bypass Angular's templating and make custom UI changes that can't be expressed declaratively. For example if you need to set a property or an attribute whose name is not statically known, use the setProperty() or setAttribute() method.


1 Answers

Try this:

   @HostListener('focus') onFocus() {
    this._renderer.setStyle(this._el.nativeElement, 'width', '200px');

BTW Renderer is deprecated, so Renderer.setElementStyle was changed to Renderer2.setStyle.

like image 82
Denis Levkov Avatar answered Oct 05 '22 17:10

Denis Levkov