Search code examples
angularsvgxlink

Angular 2 template with SVG <textPath> xlink:ref attribute not referencing associated <path> via ID


I have an Angular 2+ component that has SVG in it's template, and it works well.

template: `
<svg:path class="OutlineSegment" [attr.d]="svgPath" id="outlineSegmentPath"></svg:path>
<svg:text class="DartDistanceOnSeam">
    <svg:textPath alignment-baseline="top" xlink:href="#outlineSegmentPath">
       {{ length | number: '1.2-2' }} {{ displayUnit }}
    </svg:textPath>
</svg:text>
`

Alas, all the text is rendered along the same path for all instances of the component, since they seem to be referencing the same #outlineSegmentPath.

I can't seem to target the particular path created in this component. Of course the path's ID attribute is static in the template.

Do I need to generate unique IDs myself, or is their an Angular way to knitting together IDs and xlink:href references within a component?


Solution

  • I solved this by generating my own id to render in the path and textPath tags. I used UUIDs.

    private _id: string;
    get id(): string { 
        if (!this._id) {
          this._id = UUID.UUID();  // from from 'angular2-uuid'
        }
        return this._id;
    }
    get hashId(): string {
      return `#${this.id}`;
    }
    

    and in the template:

    <svg:path [attr.d]="svgPath" [attr.id]="id"></svg:path>
    <svg:text dy="-4">
        <svg:textPath [attr.xlink:href]="hashId">
            {{ length | number: '1.1-1' }} {{ displayUnit }}
        </svg:textPath>
    </svg:text>