How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas?

Currently, I have converted webpack starter for use with Angular:

This is the code inside square.component.template.html:

<h1>My component</h1>
<p>first paragraph</p>
<div class="container">
<form (ngSubmit)="draw(counter.value)" autocomplete="off">

    <input [value]="counter.value" (input)="counter.value = $event.target.value" placeholder="Number of squares" autofocus>

    <button md-raised-button color="primary">Submit Value</button>
</form>
<canvas width="350" height="800"></canvas>

The content of square.component.ts is as follows:

import { Component } from '@angular/core';


@Component({
  selector: 'square',
  templateUrl: './square.component.template.html'
})
export class DetailComponent {
   // Set our default values
   counter = { value: '' };
   constructor() {

}

 ngOnInit() {
   console.log('hello `Detail` component');
 }

draw(value: number) {
console.log('counter', value);
for (var i = 0; i < value; i++) {
  var canvas = document.querySelector("canvas");
  var context = canvas.getContext("2d");

  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  context.fillStyle = color;
  context.fillRect(10, 10, 100, 50);
}
this.counter.value = 0;
}

The current issue is that it only draws a square in one location. Additionally, if a value greater than 50 is entered, the browser crashes. Since I am new to Angular2, I require some assistance. Can you offer any guidance?

Answer №1

To ensure that each box is positioned uniquely on the canvas, you can modify the code as follows:

 draw(value: number) {
  console.log('counter', value);
  var canvas = document.querySelector("canvas");
  var context = canvas.getContext("2d");
  var topPos = 10;
  for (var i = 0; i < value; i++) {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var j = 0; j < 6; j++) {
    color += letters[Math.floor(Math.random() * 16)];
    }

  context.fillStyle = color;
  context.fillRect(10, topPos , 100, 50);
  topPos = topPos + 55
 }
this.counter.value = 0;
}

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

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

Ways to trigger a function in Angular every 10 seconds

What is the method to utilize Observable function for fetching data from server every 10 seconds? Custom App service fetchDevices (): Observable<Device[]> { return this.http.get(this.deviceUrl) .map(this.extractData) .catch(this ...

Cyber Platform

I recently encountered a challenge while working on my web project. What are some areas that can be improved? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map} from 'rxjs/op ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

Reorganizing the layout of a React grid in response to changes in screen size

Currently, I'm facing a challenge in creating a container for a React app that includes a Highcharts chart and three textboxes. My struggle lies in getting the three textboxes to adjust and rearrange beneath the chart component when resizing the scree ...

Newbie seeking help with Angular Services

I'm struggling to avoid duplicating code by using a service. How can I refactor this into a service and then utilize it in the component? Any assistance would be greatly appreciated. function navigateToLink(myRecords) { this.targetLink = this.data.l ...

Unable to find a solution for 'thrift'

After installing thrift on my Windows 10 machine, I attempted to run an Angular service that utilizes thrift generated files. In the package.json file, I included: "@types/thrift": "^0.10.9", "thrift": "^0.13.0", but every time I try to run it, I e ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

How to implement a dynamic tag using TypeScript in React?

How can I implement dynamic tag typing in React using TypeScript? Take a look at the following code snippet: interface CompProps { tag: string; } const MyComponent: React.FunctionComponent<CompProps> = ({ tag = "div", children }) => { co ...

Comparing tsconfig.json and tsconfig.build.json: what sets them apart?

Guides like those found at 1 and 2 often recommend having two separate files - tsconfig.json and tsconfig.build.json - at the root level of an NPM monorepo for TypeScript projects. What are the distinctions between these files? Is it possible to consolida ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

What are the tips for using ts-node in the presence of errors?

While developing, I have encountered some issues with ts-node. When I need to test something, commenting out code is my usual approach. However, when using ts-node, I keep getting this error message: 'foo' is declared but its value is never rea ...

Having difficulty casting the parameter type from Array.find() in TypeScript

In my codebase, I am dealing with the OrganisationInterface type: export declare interface OrganisationInterface { documents?: { [documentType: OrganisationDocumentTypesList]: { // enum id: string; name: string; ...

Tips for configuring VS Code to automatically change a callable property to an arrow function instead of a standard function

When interacting with ts/tsx files in VS Code, the autocompletion feature for callable properties offers two options: propertyName and propertyName(args): However, selecting the second option generates a standard function: I would prefer to use an arrow ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...