Reputation: 447
I use 4.4.4 version of Angular. In my app.component.html
i have this code
<button class="btn btn-primary" (click)="updatePosition()">Up</button>
<svg id="svg">
<image xlink:href="../assets/map.png" x="0" y="0" height="420px" width="420px"/>
</svg>
I want to dynamically update x
and y
value when the button is pressed. I tried various methods to do that with no result.
for example i used property binding [style.x.px]="variableX"
to define x
position but despite pressing the button and updating variableX value nothing happed so it looks like i still have to update x
position. Normally i would target that image with simple javascript and do el.setAttribute('x', value)
on it, but in angular it isn't that simple or just doesn't work for some reason.
Can anybody help? :)
Upvotes: 1
Views: 6341
Reputation: 614
In order to bind to SVG element attributes In angular 2, you must prefix them with attr., e. g.:
<svg>
<circle [attr.r]="myRadius" cx="50" cy="50"></circle>
</svg>
This is a great blog explaining issues with svg bindings in Angular 2: https://500tech.com/blog/all/svg-in-angular-2/
Upvotes: 4
Reputation: 1275
If you just want a way to manipulate the x and y css properties of the image, I would use either:
NgStyle
directive to dynamically get whatever value you want like so:
<button class="btn btn-primary" (click)="updatePosition()">Up</button>
<image xlink:href="../assets/map.png" height="420px" width="420px [ngStyle]="style" />
position = { 'x': '0', 'y': '0' };
//you can also add any other css properties to this like width and height
get style() {
return this.position;
}
updatePosition() {
this.position = { 'x': '10px', 'y': '10px' }; //however you update the values
}
Or use a local ElementRef
and @ViewChild
and manipulate the nativeElement directly in your ts like so:
<button class="btn btn-primary" (click)="updatePosition()">Up</button>
<image xlink:href="../assets/map.png" height="420px" width="420px" #image/>
@ViewChild('image') image: ElementRef;
updatePosition() {
this.image.nativeElement.style.x = '10px'; //however you update the values
this.image.nativeElement.style.y = '10px'; //however you update the values
}
Make sure you import ViewChild
from "@angular/core" if you do this.
I haven't tested this in plunkr or anything, but I believe they should both work.
Upvotes: 2