Stop execution with a called function [duplicate]

I want to know if is there something I can do like below and why it’s not work

const isGameOver = () => {
    
    if(onOff.getCounter() > 0){
        console.log('Game Over')
        return false
    }
}
const play = (pos) => {
    // Set all changes after every move on the game
    
    const isFieldEmpty = gameBoard.isEmpty(pos);

    // Verify if game is over
    isGameOver()

    //Try to Move
    getPlayerToMove().setMove(pos);
    
    // Verify result the game after move
    verifyResult();

    // Change turn counter
    changeTurnCounter(isFieldEmpty);
       
};

Why the return on isGameOver() not stop the play function? And is there something to use without put an if on play()?

Why doesn’t this “toggle visibility” of React-Native component?

I’m new to ‘React-Native’ and looking for a simple, straightforward way to toggle visibility of elements. Why won’t this code of mine “show/hide” the icon? It’s a simple useState and useEffect right?

const [isDisabled, setIsDisabled] = React.useState('opacity:0')
React.useEffect(() => {
        const emailIsValid = regexEmail.test(email)
        console.log(emailIsValid)
        if(emailIsValid) {
            setIsDisabled('opacity:0')
        } else {
            setIsDisabled('opacity:100')
        }
        
    }, [email])

return (
        
        <View style={styles.container}>
            
            
            <TextInput 
                style={styles.textInput}
                placeholder="Email address"
                value = {email}
                onChangeText={text=>setEmail(text)} />

            <EvilIcons name="exclamation" size={24} color="orange" style={{isDisabled}}/> /*this one!*/
             

            <TextInput 
                style={styles.textInput}
                placeholder="Password"
                value={password}
                onChangeText={text=>setPassword(text)}
                secureTextEntry />
            
            <TextInput 
                style={styles.textInput}
                placeholder="Confirm password"
                value={confirmPassword}
                onChangeText={text=>setConfirmPassword(text)}
                secureTextEntry />

            <Button 
                disabled={submitDisabled}
                style={styles.buttonLogin}
                title='Register'
                onPress={submitRegister} />
   
        </View>
        
    ) 

Why does the Javascript function return right away even with await?

I’m newer to JavaScript and struggling to understand why this function just returns right away, even though I added an await. The code below is the minimal example to replicate what I am attempting to do. When I call add_user() from add(), id is undefined because add_user() is returning right away instead of waiting for completion of the query. I added the console log to verify that row.id is the value I expected (i.e. 1).

'use strict';

import sqlite3 from 'sqlite3'
import { open } from 'sqlite';

async function add_user(value) {
   await (async () => {
      const db = await open({
         filename: dbFile,
         driver: sqlite3.Database
      })

      const row = await db.get(`SELECT id FROM Users WHERE name LIKE "${value}"`)
      console.log(row.id)
      return row.id
   })()
}

async function add(req, res) {
    var id = await add_value(req.body.value)
    console.log(id)
}

Javascript Delete first n lines from HTML content where lines could have multiple tags at the end

So as I mentioned in the question, I have following block of HTML content that’s coming from backend, and I want to remove first (n) number of lines(n=3 or n=2), where a line could contain multiple <br/> tags adjacent like <br/><br/> or <br/><br/><br/> such that, this content:

Are you sure you want to replace the following?<br/><br/>
<br/>
Replace <b><i>[FindText]</i></b> with <b><i>[ReplaceText]</i></b><br/>
Text1 [Field1]: 3 Instances<br/>
Text2 [Field2]: 0 Instances<br/>

, after JS regex(probably or not) replacement becomes:

Text1 [Field1]: 3 Instances<br/>
Text2 [Field2]: 0 Instances<br/>

I have this Regex pattern ^.*<br/>+$ match but that doesn’t exactly work as expected, and as I afore-mentioned, my requirements are specific.

how can i save quantity to local storage

working on a cart app – when the quantity gets bought it supposed to make the button disabled but
if I refresh it becomes active again , anyone knows how to save it to local storage?

import { Button } from 'react-bootstrap';
import { Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useContext } from 'react';
import Rating from './Rating';
import axios from 'axios';
import { Store } from '../Store';

function Product(props){

    const {product} = props;

    const {state , dispatch:ctxDispatch} = useContext(Store);
    const {cart: {cartItems}} = state

    const addToCartHandler = async (item )=>{
      const existItem = cartItems.find((x)=> x._id === product._id);
       const quantity = existItem ? existItem.quantity+1:1 ; 

      const {data} = await axios.get(`/api/products/${item._id}`);
      if(data.countInStock < quantity){
          window.alert('sorry product is out of stock')
          return;
      }
  product.countInStock--
       ctxDispatch({
           type:'CART_ADD_ITEM' 
           , payload:{...item , quantity},
       });
      };
      

    return(

        <Card>


        <Link to={`/product/${product.slug}`}> 
          <img src={product.image} className="card-img-top" alt={product.name} />
        </Link>
        <Card.Body>
        <Link to={`/product/${product.slug}`}>
            <Card.Title>{product.name}</Card.Title>
        </Link>
        <Rating rating={product.rating} numReviews={product.numReviews} />
        <Card.Text>${product.price}</Card.Text>

        {  product.countInStock === 0 ? (

          
          <Button  color="light" disabled={true} >  Out of stock</Button>
          
        ):(
          
          <Button onClick={() => addToCartHandler(product)}>Add to cart</Button>
        )}
      </Card.Body>
    </Card>
    )}

product.countInStock is what needed to be saved to local storage

How to delay half a second in jQuery on click?

I have a small script with which I can sort the elements on the page by simply dragging and dropping them. On the computer everything works fine, but on the phone there is a problem. As soon as I touch the phone’s display to scroll down the page, an element with a block on the page is captured from me and dragged to the bottom in the same way. Is it possible to implement clicking on an element for 0.5-1 seconds and then dragging it?

<script type="text/javascript">
            $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
            });

            $(document).ready(function () {
            $('table tbody').sortable({
                update: function (event, ui) {
                    $(this).children().each(function (index) {
                            if ($(this).attr('data-position') != (index+1)) {
                                $(this).attr('data-position', (index+1)).addClass('updated');
                            }
                    });

                    saveNewPositions();
                }
            });
            });

            function saveNewPositions() {
                var userId = {{$user->id}};
                var positions = [];
                $('.updated').each(function () {
                positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
                $(this).removeClass('updated');
                });

                $.ajax({
                url: "ppp/sort",
                method: 'POST',
                dataType: 'text',
                data: {
                    update: 1,
                    positions: positions
                }, success: function (response) {
                        console.log(response);
                }
                });
            }
        </script>

How to use DTOs efficiently to validate request params/query params and request body in Node js using Javascript

I want to implement validation of request body / request params / query params for all the routes available in my application before passing the required data from controllers to services. I think the best way I can do that is by making use of DTOs, I have used DTOs in NestJS (Typescript) but this application has been written using Javascript, How can I implement this in Javascript ?, Also please let me know if any other better approach exists.

Error when making multiple external API requests on server (444)

I have an app that pulls data from an external API. This data comes with an images field that holds 20 or so images as remote URLs. I have a function that fetches each image, resizes it, and uploads it to cloudinary. Everything works great locally, but when I deploy my code to the server, I can only fetch 2 images and then my requests return this error:

{ 
  "message": "Request failed with status code 444",
  "name":"AxiosError",
  "config": {
    "transitional"{ 
      "silentJSONParsing": true,
      "forcedJSONParsing":true,
      "clarifyTimeoutError":false},
      "transformRequest": [null],
      "transformResponse":[null],
      "timeout":0,
      "xsrfCookieName":"XSRF-TOKEN",
      "xsrfHeaderName":"X-XSRF-TOKEN",
      "maxContentLength":-1,
      "maxBodyLength":-1,
      "env":{},
      "headers": {
        "Accept": "application/json, text/plain,*/*",
        "ContentType":"application/json",
        "User-Agent": "axios/0.27.2"
      },
     "responseType":"arraybuffer",
     "method":"get",
     "url":"https://listing-images.homejunction.com/gsrein/1018980896/photo_2.jpg" 
    },
  "code":"ERR_BAD_REQUEST",
  "status":444
}

Here is the code for the API request that fetches the image:

  const input = await axios
    .get(image, {
      responseType: 'arraybuffer',
      headers: {
        ContentType: 'application/json',
      },
    })
    .then((res) => res.data);

I am using Firebase in the project. Originally, this code was deployed to a cloud function. After encountering the error, I assumed it was a Firebase issue. I wrote up a quick express app and deployed it to Heroku and am receiving the same error. Again, this works fine when running the code locally and I am able to fetch and resize all 20 images. Any idea how I can achieve this on a remote server??

How can i calculate the rating in the rating array and still return it as a response

This is the sample JSON response from the Backend, the rating is in ratings array and the value is rating, so I want to calculate the average rating for each course and still return it as a response to frontend,
I tried using Object.Assign() but is worked well when i am fetching just one course but when i am fetching all courses, it doesn’t work.

please i need help

{
    "message": "Fetched successfully",
    "status": "Success",
    "statusCode": 200,
    "data": {
        "items": [
            {
                "id": 210,
                "courseUuid": "93b760a7-505e-41bf-b57e-d84ecf53255f",
                "userId": 2,
                "title": "Complete Angularzero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655654436946-f02118c8-e3e9-44e5-8913-48d4f45cd816.png",
                "slugUrl": "Complete-Angularzero-to-hero-19-06-2022-93b760a7-505e-41bf-b57e-d84ecf53255f",
                "amount": "50,600",
                "averageRating": "11.5",
                "createdAt": "2022-06-19T16:00:43.009Z",
                "updatedAt": "2022-06-19T23:27:46.073Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "[email protected]",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [
                    {
                        "id": 1,
                        "paymentStatus": "Not Completed",
                        "createdAt": "2022-06-19T16:04:22.375Z",
                        "user": {
                            "id": 3,
                            "userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
                            "email": "[email protected]",
                            "nawisNumber": "NAWIS/2022/12758991"
                        }
                    },
                    {
                        "id": 2,
                        "paymentStatus": "Not Completed",
                        "createdAt": "2022-06-19T16:07:37.059Z",
                        "user": {
                            "id": 6,
                            "userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
                            "email": "[email protected]",
                            "nawisNumber": "NAWIS/2022/11177867"
                        }
                    }
                ],
                "ratings": [
                    {
                        "id": 1,
                        "rating": 2,
                        "review": "some text here",
                        "createdAt": "2022-06-19T16:04:40.339Z",
                        "user": {
                            "id": 3,
                            "userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
                            "email": "[email protected]"
                        }
                    },
                    {
                        "id": 2,
                        "rating": 5,
                        "review": "some text here",
                        "createdAt": "2022-06-19T16:07:23.798Z",
                        "user": {
                            "id": 6,
                            "userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
                            "email": "[email protected]"
                        }
                    }
                ]
            },
            {
                "id": 208,
                "courseUuid": "16855bd6-dd18-420a-8611-bc77bbda818c",
                "userId": 2,
                "title": "Complete Vuejs zero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653347091-cfee6022-0d3a-43e2-b780-986eda2607ed.png",
                "slugUrl": "undefined-19-06-2022-16855bd6-dd18-420a-8611-bc77bbda818c",
                "amount": "0",
                "averageRating": "0",
                "createdAt": "2022-06-19T15:42:30.273Z",
                "updatedAt": "2022-06-19T15:53:07.726Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "[email protected]",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [],
                "ratings": []
            },
            {
                "id": 207,
                "courseUuid": "bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
                "userId": 2,
                "title": "Complete Vuejs zero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653325613-dda17c5c-2a4a-435a-99cb-ad28ea01bbb0.png",
                "slugUrl": "Complete-Vuejs-zero-to-hero-19-06-2022-bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
                "amount": "50,600",
                "averageRating": "0",
                "createdAt": "2022-06-19T15:42:12.687Z",
                "updatedAt": "2022-06-19T15:42:12.687Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "[email protected]",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [],
                "ratings": []
            }
        ],
        "meta": {
            "totalItems": 209,
            "itemCount": 3,
            "itemsPerPage": 6,
            "totalPages": 35,
            "currentPage": 1
        },
        "links": {
            "first": "http://ourakademy.com/api/v1/courses?limit=6",
            "previous": "",
            "next": "http://ourakademy.com/api/v1/courses?page=2&limit=6",
            "last": "http://ourakademy.com/api/v1/courses?page=35&limit=6"
        }
    }
}

Running a C# function on an onclick to modify SVG file

I have an ASP.NET Core MVC application with a couple of coded in functions in the .cshtml pages(Razor). This one in particular I’d like to run when an a-tag gets clicked on. This code will essential will go to a locally stored .svg file and change some of the styling attributes. The code for that is below, and is stored in the View.

public static void turnRed()
{   
    var pathToSVG = "path/to/svg";
    var doc = XDocument.Load(pathToSVG);
    var node = doc.Descendants(XName.Get("rect", "http://www.w3.org/2000/svg")).FirstOrDefault(cd => cd.Attribute("id").Value == "rect1");

    node.SetAttributeValue("fill", "red");

    doc.Save(pathToSVG);


}

Now in the actual html I would like to have a simple onclick expression that would run the code when the a-tag gets pressed.

    <a onclick="@{ turnRed(); }" href="#">Change SVG color</a>

What I have right now for whatever reason gets called onload, and not on click. How might I go about this? If there’s a way to to do it without JavaScript, that would be ideal, but whatever works. Thanks!

Here are some of the concepts I’ve looked at and tried already:

Using Razor to call C# function

https://www.c-sharpcorner.com/blogs/how-to-create-razor-function-in-asp-net-mvc-view1

https://asp.mvc-tutorial.com/razor/local-functions/

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-6.0

Difference between setState class comp and function comp

I’m trying to update a class based component to a function component. but I’m facing issues with the state. in the function component, the state is not updated. after trying to debug this, there seems to be something wrong with this line: setState(func(...args))

any suggestions?

_. is lodash

export default class BPM extends React.Component {
  state = { ..._.cloneDeep(bpmFlowInitialValues) };

  render() {
    const chart = this.state;
    const stateActions = _.mapValues(
      callbacks,
      (func) =>
        (...args) =>
          this.setState(func(...args))
    );

    console.log(this.state);

    return (
      <>
        <ShapesHeader />
        <Box sx={{ display: 'flex', flexWrap: 'wrap' }}>
          <Flowchart chart={chart} stateActions={stateActions} />
          <Sidebar selected={this.state.selected} />
        </Box>
      </>
    );
  }
}

function comp:

export default function BPM() {
  const [state, setState] = React.useState({
    ..._.cloneDeep(bpmFlowInitialValues),
  });

  const stateActions = _.mapValues(
    callbacks,
    (func) =>
      (...args) =>
        setState(func(...args))
  );

  console.log('state', state);

  return (
    <>
      <ShapesHeader />
      <Box sx={{ display: 'flex', flexWrap: 'wrap' }}>
        <Flowchart chart={state} stateActions={stateActions} />
        <Sidebar selected={state && state.selected} />
      </Box>
    </>
  );
}

React is not showing anything on the screen

I was using function instead of class and the code was working up to certain extent, now it is not displaying at all.

In my VehiclesList.js I generate 10 random vehicles, code below:

import React from 'react'
import {faker} from '@faker-js/faker'
import ListGroup from 'react-bootstrap/ListGroup';
import Vehicles from './Vehicles';

class VehicleList extends React.Component {
  constructor(props){
    super(props);
    this.manufacturer = this.faker.vehicle.manufacturer().bind(this)
  }

   render(){
   return (
    <div style={{ display: 'block', width: 400, padding: 30 }}>
        <ListGroup>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
      </ListGroup>
    </div>
  );
}
}

export default VehicleList

In my vehicle.js I have to show the info of the clicked vehicle, react is not showing anything on the screen and I’m lost at this point.

The code below:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Card, Button} from 'react-bootstrap';
import VehicleList from './VehicleList';
import {faker} from '@faker-js/faker'
import ListGroup from 'react-bootstrap/ListGroup';

class Vehicles extends React.Component{
  constructor(props){
    super(props);
    this.manufacturer = this.faker.vehicle.manufacturer().bind(this)
  }
  render(){
  return(
<div>
<Card className="text-center">
  <Card.Body>
    <Card.Title>No Vehicle Selected</Card.Title>
    <Card.Text>
      Click a vehicle to see more details
    </Card.Text>
  </Card.Body>
  </Card>
<br></br>
  <Card style={{ width: '18rem' }}>
    <Card.Img variant="top" src={`https://via.placeholder.com/180x150?text=${faker.vehicle.manufacturer()}
     ${faker.vehicle.model()}`} />
    <Card.Body>
    <Card.Title>{faker.vehicle.manufacturer()} {faker.vehicle.model()}</Card.Title>
      <Card.Text>
      This is a wonderful {faker.vehicle.fuel()}-powered {faker.vehicle.color()} {faker.vehicle.type()}.
      </Card.Text>
      <Button variant="primary">Buy now!</Button>
    </Card.Body>
</Card>
</div>
)
}
}


export default Vehicles

I really appreciate any help with this. Thanks!

Mat-Checkbox not working: What could the problem be?

This is what I tried doing:


<h1 mat-dialog-title> Service settings </h1>
<div class="inputgrid">
    <label for="visualizationInput"> Visualization server address </label>
    <input id="visualizationInput" matInput type="text" name="visualization" [value]="server"
        (input)="server = $event.target.value">
    <label for="lookupInput"> Assembly service address </label>
    <input id="lookupInput" matInput type="text" name="lookup" [value]="lookup" (input)="lookup = $event.target.value">
    <label for="gatewayInput"> API gateway address </label>
    <input id="gatewayInput" matInput type="text" name="gateway" [value]="gateway"
        (input)="gateway = $event.target.value">
    <input type="checkbox" id="gltf" (click)="ShowGLTFDataFormat()" /> Activate GLTF Data Transfer Format
</div>
    <mat-checkbox (change)="ShowGLTFDataFormat()">Activate GLTF Data Transfer Format</mat-checkbox>
<div mat-dialog-actions>
    <button mat-button (click)="onNoClick()">Discard</button>
    <button mat-button cdkFocusInitial (click)="updateAddresses()">Save</button>
</div>

My module.ts looks somewhat like this.

import { NgModule } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PortalModule } from '@angular/cdk/portal';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { CdkStepperModule } from '@angular/cdk/stepper';
import { CdkTableModule } from '@angular/cdk/table';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
import { OverlayModule } from '@angular/cdk/overlay';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
    exports: [
        A11yModule,
        ClipboardModule,
        CdkStepperModule,
        CdkTableModule,
        CdkTreeModule,
        DragDropModule,
        MatAutocompleteModule,
        MatBadgeModule,
        MatBottomSheetModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatDividerModule,
        MatExpansionModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatNativeDateModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatFormFieldModule,
        OverlayModule,
        PortalModule,
        ScrollingModule,
    ]
})
export class MaterialModule { }

But I keep getting this error: 5 – error NG8001: ‘mat-checkbox’ is not a known element:

  1. If ‘mat-checkbox’ is an Angular component, then verify that it is part of this module.
  2. If ‘mat-checkbox’ is a Web Component then add ‘CUSTOM_ELEMENTS_SCHEMA’ to the ‘@NgModule.schemas’ of this component to suppress this message.

13 <mat-checkbox (change)=”ShowGLTFDataFormat()”>Activate GLTF Data Transfer Format

I don’t know what’s wrong and I would extremely appreciate any help whatsoever about this as I am new to coding and I need this done as soon as possible.

JavaScript animate element when key is pressed

I want to create a script where my HTML-div is being animated everytime a key is pressed. Here is my code:

let square = document.querySelector("div")

document.addEventListener("keydown", function(e) {
    square.style.animation = "shake 0.5s"
    square.style.animationIterationCount = "infinite"   
})

My problem is, if I exclude the last line where I set animation-iteration-count to "infinite", it works once, and if I press the button again, it won’t work anymore. But if I set it to “infinite”, the animation won’t stop. How can I set it so that I see the animation every time I press a button, but without having the animation all the time? Thanks for any suggestion!