Angular 2 : Controlling SVG Image/Icon Css Styles dynamically through user inputs/events on UI

只愿长相守 提交于 2019-12-25 09:15:58

问题


I used Jquery to control the Css styles of svg image dynamically in Angular 2.

1: Control using events like mouse hover

Below is a sample code for a simple circle .svg image with initial styles defined and a mouseover event on circle which will trigger 'func1' on hovering the circle:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 175.7 177" style="enable-background:new 0 0 175.7 177;" xml:space="preserve">

<style type="text/css">
.st0{
   fill:#FFFFFF;
   stroke:#000000;
   stroke-width:4;
   stroke-miterlimit:10;
 }
</style>
<circle id="XMLID_1_" class="st0" cx="91.2" cy="87.2" r="10"    (mouseover)="func1()"/>

Now define this function: func1() in its corresponding component (.ts file) with the styles you want to be changed using jquery. It will look like this:

func1(){
   console.log("func1 has been called!");
   $(".st0").css({"stroke":"yellow", "fill": "blue"});
}

Try to explore other events also (like 'click').

2. Control by taking form inputs

If you want to change styles of svg using form inputs you should use dynamic binding. Sample additional code (along with previous svg code) in template:

<form>
    Stroke<input type="text" name="stroke" [(ngModel)]="stroke">
    Fill<input type="text" name="fill" [(ngModel)]="fill">
    <button (click)="submit()">Submit</button>
</form>

Code need to be added in corresponding component (.ts file):

stroke:any;
fill:any;

submit(){
   console.log("submit called!"+ this.stroke+" and  "+ this.fill);
   $(".st0").css({"stroke":this.stroke, "fill": this.fill});
}

回答1:


Just use the ngStyle directive

<circle [ngStyle]="{stroke:stroke, fill: fill}" 
    id="XMLID_1_" 
    class="st0" cx="91.2" cy="87.2" r="10"    
    (mouseover)="func1()"/>

Just use the ngStyle directive

<circle [style.stroke]="stroke"
        [style.fill]="fill" 
    id="XMLID_1_" 
    class="st0" cx="91.2" cy="87.2" r="10"    
    (mouseover)="func1()"/>

Try to avoid using jQuery with Angular2.



来源:https://stackoverflow.com/questions/42200443/angular-2-controlling-svg-image-icon-css-styles-dynamically-through-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!