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.
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.
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.
constructor(public el: ElementRef, public renderer: Renderer){
this.myDiv = <HTMLElement>(document.createElement('div'));
renderer.setElementStyle(this.myDiv , 'width', this.progress()+'%');
}
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:
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
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