Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add [ngStyle] directive dynamically in ionic 3 / angular

This is what I had and it was working, it was bounded to progress method and it was displaying correctly:

<div [ngStyle]="{'width.%': progress()}"></div>

Now I have to create the element dynamically:

let myDiv = <HTMLElement>(document.createElement('div'));

but I can't seem to find a way to bind the progress method to my dynamically created element.

Code using renderer as suggested by @fatemefazli which doesn't have change detection so it doesn't render when data becomes available nor listens to change of progress method: https://stackblitz.com/edit/angular-fpyfmn

The decision to create DOM elements dynamically comes from the need to attach pan gesture using HammerJS which requires to attach a listener like so:

addGestures(elem){
    var hammer = new Gesture(elem);
    hammer.listen();

    hammer.on('pan', (e) => this.Pan(e));
  }

I tried to create an event publish / emitter but I don't have a trigger to publish it.

like image 262
August Avatar asked Jun 04 '18 19:06

August


People also ask

How do you set up NgStyle?

NgStylelinkAn attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional . <unit> suffix (such as 'top.

What is the use of NgStyle directive?

The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green. The above code uses the ternary operator to set the background color to green if the persons country is the UK else red.


2 Answers

constructor(public el: ElementRef, public renderer: Renderer){
    this.myDiv = <HTMLElement>(document.createElement('div'));
    renderer.setElementStyle(this.myDiv , 'width', this.progress()+'%');
}
like image 96
Fateme Fazli Avatar answered Sep 20 '22 23:09

Fateme Fazli


As TricheTriche said, you shouldn't directly access the DOM. In fact, not only it's not recommended but will not work for dynamic changes, since it's not really running inside the angular zone anymore.

What you need to do is:

  1. create a new placeholder in your current component that will host (2)
  2. create a new directive that is in charge of listening and handling events , and also rendering any style changes
  3. use ComponentFactoryResolver to dynamically inject (2) into (1)

Check more details on Angular's page Angular's Dynamic Component Load page, in which they present a running example of something similar to what you need

like image 32
WebDever Avatar answered Sep 20 '22 23:09

WebDever