Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far:

my-component.js:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-component',
    templateUrl: 'my-component.html'
})

export class MyComponent{
  lines: [
    { weight: 0.4, x1: 86.69, y1: 1, x2: 98.91, y2: 1 },
    { weight: 0.5, x1: 85.31, y1: 9.67, x2: 98.23, y2: 9.67 }
  ]
}

my-component-html:

<svg id="lines" viewBox="0 0 320.6 542.59" *ngFor='line of lines'>
  <line class="line" [attr.x1]="{{ x1 }}" [attr.y1]="{{ y1 }}" [attr.x2]="{{ x2 }}" [attr.y2]="{{ y2 }}"/>
</svg>

There are some syntax errors in my code, causing it not to work properly. I need help in identifying and correcting these mistakes.

Answer №1

Avoid combining binding and interpolation. Here's a better approach:

<svg id="lines" viewBox="0 0 320.6 542.59" >
  <line *ngFor="let line of lines" class="line" [attr.x1]="line.x1" [attr.y1]="line.y1" [attr.x2]="line.x2" [attr.y2]="line.y2"/>
</svg>

Make sure to replace : with = in your component as well

export class MyComponent{
  lines = [ // specify your values here
    { weight: 0.4, x1: 86.69, y1: 1, x2: 98.91, y2: 1 },
    { weight: 0.5, x1: 85.31, y1: 9.67, x2: 98.23, y2: 9.67 }
  ];
}

Answer №2

JUST AN IDEA

Perhaps you could consider using the ngx-svg module as an alternative solution. This module makes generating SVG objects a breeze. To implement the code mentioned above, simply include the module and then use the following in your view -

<svg-container containerId="lineContainer">
  <svg-line *ngFor="let line of lines" [borderSize]="line.weight" [x0]="line.x1" [y0]="line.y1" [x1]="line.x2" [y2]="line.y2"></svg-line>
</svg-container>

In addition to the parameters mentioned, you can also listen for various events such as onClick, onMouseOver, onMouseOut, onDoubleClick, and customize the border color.

Furthermore, besides creating line svg objects, this library allows you to generate different objects like ellipses, rectangles, polylines, polygons, and more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock the full potential of Angular lazy loaded modules by gaining access to root services

Exploring the world of Angular lazy loaded modules, I have a question about accessing a root service called AuthService within lazy loaded modules. My goal is to tap into the singleton instance present in the root injector while working with these modules. ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

What is the method for adjusting the border color of an ng-select component to red?

I am having an issue with the select component in my Angular HTML template. It is currently displaying in grey color, but I would like it to have a red border instead. I have tried using custom CSS, but I haven't been able to achieve the desired resul ...

Displaying individual information for each Bootstrap modal in Angular can be achieved by properly binding the data

While looping through images, a modal pops up with its information when clicked. The issue is that all the modals associated with different images display the same content as the first image. This is what has been attempted: data:any; HTML <div *ngFo ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

Tips for accurately defining prop types in next.js when utilizing typescript?

Here is the content of my index.tsx file: import type { NextPage } from "next"; type AppProps = { articles: { userId: number; id: number; title: string; body: string; }; }; con ...

What is the best way to make a class available in the global namespace within a TypeScript module?

The Issue at Hand Given an existing application with a mixture of modules and global scripts, the goal is to convert one class in a global script (gamma.ts) into a module. This entails adding `export default` before `class gamma {}` in gamma.ts. Additiona ...

Unable to link with 'NgModel' as it is not recognized as a valid property of 'ion-input'

I'm experiencing some difficulty with the following error message: Error: Uncaught (in promise): Error: Template parse errors: Can't bind to 'NgModel' since it isn't a known property of 'ion-input'. 1. If 'ion-input ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

Angular 7 - Customize Mat-select-value color depending on a specific condition

One issue I am facing is changing the color of a selected value in a mat select based on a condition. This change should be visually apparent to the user. Although accessing mat-select-value from the styles is possible, implementing a condition using ng-cl ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Encountering a TypeScript error in Next.js: The 'Options' type does not align with the 'NavigateOptions' type

My code snippet: import { useRouter } from 'next/navigation'; interface Options { scroll: boolean; } const Component = () => { const router = useRouter(); const updateSearchParams = () => { const searchParams = new URLSearchPa ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Unexpected date format displayed by the flat picker calendar

The expected date format is "DD-MM-YYYY" but the shown date format in the UI is "YYYY-MM-DD". Click here to view the UI image Initially, before opening the date picker, the date is displayed in the expected format as "DD-MM-YYYY". Upon opening the date p ...

Traversing through JSON objects in Angular 2

I am currently facing an issue while trying to iterate through a JSON object. Below is the sample JSON data: floors.ts this.floors= [ { floorName: "floor 1", result: [ { resFloor: "1", ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Error message: The function _this.$(...).modal is not defined for the OpaqueToken jQuery in Angular-cli

I'm facing an issue with using jQuery in Angular2. I can't seem to get my modal to pop out. Error message: I used Angular-cli npm install and then yarn to install bootstrap + In my .angular-cli.json file, I have the following scripts: "script ...

Navigating through a typescript array containing various types and mapping each element

Is there a way to get [valueOfTypeOne, ValueOfTypeTwo] instead of (valueOfTypeOne | ValueOfTypeTwo)[] for each resulting element in this scenario? const [valueOfTypeOne, ValueOfTypeTwo] = await Promise.all( [ fetchTypeOne(), fetchTypeTwo( ...