textarea on vue not accepting null - node.js

I use:
- "vue": "3.2.26",
- "vee-validate": "4.5.6",
- "typescript": "4.5.4"
While creating a textarea field on vue3 I ran into a problem
i have
example with vee-validate
import { Field, useForm } from 'vee-validate'
<Field v-slot="{ field, errors }" name="name" type="text">
<VControl icon="feather:edit-2" :has-error="Boolean(formErrors.name)">
<input
v-bind="field"
class="input is-primary-focus"
type="text"
placeholder="Placeholder"
autocomplete="name"
/>
<p v-if="errors" class="help is-danger">{{ formErrors.name}}</p>
</VControl>
</Field>
simple example
<textarea
v-model="fieldValues.description"
class="textarea is-success-focus"
rows="3"
placeholder="Description"
></textarea>
for model
export interface iCat {
id: number
name: string
description: string | null
}
but textarea return error
Type 'null' is not assignable to type 'string | number | string[] | undefined'.
for vee-validate
const {
values: fieldValues,
errors: formErrors,
handleSubmit,
} = useForm({
initialValues: {
id: 0,
name: '',
description: ''
},
validationSchema: object({
id: number().required().integer(),
name: string().required(),
description: string().notRequired().default(null).nullable()
}),
})
if check #vue/runtime-dom/dist/runtime-dom.d.ts
export interface TextareaHTMLAttributes extends HTMLAttributes {
....
value?: string | string[] | number
...
}
If I look in node-moduls, I see that the textarea does not accept null as a value - how can I properly solve this problem then?

Unfortunately, you can't change the existing type of value for TextareaHTMLAttributes (at least not in TypeScript 4.5.5). Type augmentation only allows extension (adding properties to the type, or creating a new type that extends the original TextareaHTMLAttributes interface with a new type for value).
A workaround is to use a new type that extends iCat, changing its description type to the expected type of TextareaHTMLAttributes's value:
Declare a new type (named "iFieldValues"), using Omit to exclude the original description property from iCat, and an intersection with a new description property that has a type of TextareaHTMLAttributes['value'].
Use type assertion (as iFieldValues) on the values returned from useForm().
// MyForm.vue
<script setup lang="ts">
import { toRefs } from 'vue'
import type { TextareaHTMLAttributes } from '#vue/runtime-dom'
import { useForm } from 'vee-validate'
import { object, number, string } from 'yup'
export interface iCat {
id: number
name: string
description: string | null
}
1️⃣
type iFieldValues = Omit<iCat, 'description'> & {
description: TextareaHTMLAttributes['value']
}
const {
values,
errors: formErrors,
handleSubmit,
} = useForm({
initialValues: {
id: 0,
name: '',
description: ''
},
validationSchema: object({
id: number().required().integer(),
name: string().required(),
description: string().notRequired().default(null).nullable()
}),
})
2️⃣
const fieldValues = values as iFieldValues
</script>

Related

AWS CDK error creating an ARecord for CloudFront distro

Given:
export class MyARecord extends cdk.Stack {
public readonly arecord: ARecord
constructor(scope: cdk.Construct, id: string, props: IcARecordARecordProps) {
super(scope, id, props);
const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'hostedZone', {
hostedZoneId: props.hostedZoneId,
zoneName: props.apexDomainName
})
console.log(hostedZone.hostedZoneId);
console.log(hostedZone.zoneName);
const distribution = Distribution.fromDistributionAttributes(this, 'distribution', {
domainName: props.apexDomainName,
distributionId: props.distributionId
});
this.arecord = new ARecord(this, `${props.projectName}ARecord`, {
zone: hostedZone,
target: RecordTarget.fromAlias(
new CloudFrontTarget(distribution)
)
})
}
}
Deploying I get the following logging and error:
hostedZoneId: 'Z1016966FIW9RVHP46ST',
zoneName: 'testmyroute53domain.com',
08:21:59 | CREATE_FAILED | AWS::Route53::RecordSet | testmyroute53domaincomARecordB9B947F2
[Tried to create an alias that targets testmyroute53domain.com., type A in zone Z2FDTNDATAQYW2, but the alias target name does not lie within the target zone]
Anybody have any idea why it asks about a zone 'Z2FDTNDATAQYW2' when the zone id is clearly 'Z1016966FIW9RVHP46ST'?
Manually I made the A record and it works.... Just AWS CDK does not want to create it for me...

Using Nipplejs in Vue with Quasar

i am trying to use Nipplejs in my Vue Project with quasar Components.
I installed nipplejs by npm install nipplejs --save.
I tried to integrate the nipple with the following code:
<template>
<div id="joystick_zone"></div>
</template>
<script lang= "ts">
// Imports
import Vue from "vue";
import nipplejs from 'nipplejs';
export default Vue.extend({
async mounted(): Promise<void> {
var options = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: `'blue'`,
}
var manager = nipplejs.create(options);
}
});
My first problem is that typescript doesnt accept 'static' as mode:
The definition says: mode?: 'dynamic' | 'semi' | 'static';
And i get the following error message:
Argument of type '{ zone: HTMLElement; mode: string; color: string; }' is not assignable to parameter of type 'JoystickManagerOptions'.
Types of property 'mode' are incompatible.
Type 'string' is not assignable to type '"dynamic" | "semi" | "static" | undefined'.
My second problem is that the joystick does not appear on the website.
If someone could help i would be very thankful.
If you would look into the definition of options variable you created. You would see it is of type { zone: HTMLElement; mode: string; color: string; }.
You must assign a type to the options variable.
var options: JoystickManagerOptions = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: 'blue',
};
Other option is to define the variable as const:
var options = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: 'blue',
} as const;
// Variable is now of type
type options = {
zone: HTMLElementHTMLElement;
mode: 'static';
color: 'blue';
}

Why doesn't the image from the external link work in gatsby?

Excuse me, please, I am just learning. In some gatsby templates I can insert as Image - an image from a URL and in some templates Image don't want to display it.
What does it depend on and how to edit the code to make the url work? (My knowledge about graphql is rather basic)
this is the code for the blog template:
/** #jsx jsx */
import { jsx } from 'theme-ui'
import { Link, graphql } from "gatsby"
import Img from "gatsby-image"
import { RiArrowRightLine, RiArrowLeftLine } from "react-icons/ri"
import Layout from "../components/layout"
import SEO from '../components/seo';
const styles = {
'article blockquote': {
'background-color': 'cardBg'
},
pagination: {
'a': {
color: 'muted',
'&.is-active': {
color: 'text'
},
'&:hover': {
color: 'text'
}
}
}
}
const Pagination = (props) => (
<div
className="pagination -post"
sx={styles.pagination}
>
<ul>
{(props.previous && props.previous.frontmatter.template === 'blog-post') && (
<li>
<Link to={props.previous.frontmatter.slug} rel="prev">
<p
sx={{
color: 'muted'
}}
>
<span className="icon -left"><RiArrowLeftLine/></span> Previous</p>
<span className="page-title">{props.previous.frontmatter.title}</span>
</Link>
</li>
)}
{(props.next && props.next.frontmatter.template === 'blog-post') && (
<li>
<Link to={props.next.frontmatter.slug} rel="next">
<p
sx={{
color: 'muted'
}}
>Next <span className="icon -right"><RiArrowRightLine/></span></p>
<span className="page-title">{props.next.frontmatter.title}</span>
</Link>
</li>
)}
</ul>
</div>
)
const Post = ({ data, pageContext }) => {
const { markdownRemark } = data // data.markdownRemark holds your post data
const { frontmatter, html, excerpt } = markdownRemark
const Image = frontmatter.featuredImage ? frontmatter.featuredImage.childImageSharp.fluid : ""
const { previous, next } = pageContext
let props = {
previous,
next
}
return (
<Layout className="page">
<SEO
title={frontmatter.title}
description={frontmatter.description ? frontmatter.description : excerpt}
image={Image}
article={true}
/>
<article className="blog-post">
<header className="featured-banner">
<section className="article-header">
<h1>{frontmatter.title}</h1>
<time>{frontmatter.date}</time>
</section>
{Image ? (
<Img
fluid={Image}
objectFit="cover"
objectPosition="50% 50%"
alt={frontmatter.title + ' - Featured image'}
className="featured-image"
/>
) : ""}
</header>
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</article>
{(previous || next) && (
<Pagination {...props} />
)}
</Layout>
)
}
export default Post
export const pageQuery = graphql`
query BlogPostQuery($id: String!) {
markdownRemark(
id: { eq: $id }
) {
id
html
excerpt(pruneLength: 148)
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
description
featuredImage {
childImageSharp {
fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize
}
sizes {
src
}
}
}
}
}
}
`
typical post:
---
template: blog-post
title: my title
slug: /plant/bud
date: 2020-05-13 12:37
description: abc
featuredImage: /assets/screen-post-hixmjdah9xhoo-unsplash.jpg (but online image from imgurl png doesnt work)
---
post nr 1
edited ///
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/static/assets/`,
name: `assets`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/content/`,
name: `content`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
gfm: true,
plugins: [
netlifyCmsPaths,
`gatsby-remark-reading-time`,
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1024,
showCaptions: true,
linkImagesToOriginal: false,
tracedSVG: true,
loading: "lazy",
},
},
`gatsby-remark-responsive-iframe`,
{
resolve: `gatsby-remark-prismjs`,
options: {
classPrefix: "language-",
inlineCodeMarker: null,
aliases: {},
showLineNumbers: false,
noInlineHighlight: false,
// By default the HTML entities <>&'" are escaped.
// Add additional HTML escapes by providing a mapping
// of HTML entities and their escape value IE: { '}': '{' }
escapeEntities: {},
},
},
],
},
},
In Gatsby, you can insert images from external sources using the standard HTML <img> tag with the src property:
<img src="https://via.placeholder.com/150" alt="Alt text" width="500" height="600">
If you want to keep the benefits of gatsby-image across the external (or online) images, you should need to use some dependencies to achieve lazy loading and other features.
However, to use gatsby-image you need to allow Gatsby and the inferred GraphQL schema to use their transformers (gatsby-transformer-sharp and sharps (gatsby-plugin-sharp) across with the filesystem (gatsby-source-filesystem) or in other words, Gatsby needs to have access to the images that needs to parse to create a valid queryable GraphQL schema, that will be consumed with the gatsby-image.
In addition, you need to specify the folder of your project where those images belong (setting the filesystem):
const path = require(`path`)
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}
Once the filesystem is set and the images are processed, a GraphQL node is created, and you are allowed to use the fragments like the one you've provided:
featuredImage {
childImageSharp {
fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize
}
sizes {
src
}
}
}
Since the external images can't be directly processed by Gatsby, they can't be used with gatsby-image. Depending on the source of those images, some plugins allow you to keep using gatsby-image from external sources (usually from CMSs like Contentful and others).
You can check for further documentation in Working with images docs.
Update (01/06/2021)
In the last Gatsby version (v2.30) they've added a new experimental feature, still in beta to support external images in a <StaticImage> component. To enable it, just upgrade to the latest Gatsby version (via npm or yarn) and add the following flags in your running scripts:
GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby develop
GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby build
You can then pass absolute URLs to StaticImage:
<StaticImage src="https://placekitten.com/400/400" alt="Kittin" />

Best strategy for Angular Front-End Form Building by Users [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
Good day, whoever reads this, thanks for taking the time to possibly assist!
Back in the day, I used to work a lot with Wordpress (PHP) and there was this plugin we used to gather metadata: Advanced Custom Fields (advancedcustomfields . com). What made it cool was that you could visually set up groups of questions (a form if you will), by selecting the types of questions and configure their setup and style (input with label in inside or outside, or, table with rows and columns specifying each key alongside which the answer would be saved against in the database).
I'm looking to build the exact same thing in Angular 8+, allowing my client to choose whatever type of field (input) they want and group them together. How do you suggest I go about this:
1) build custom components like: text input/area, radio, table, map, image, file upload, checkboxes, date/time pickers, select boxes, groups etc (each carrying conditional rules to show or not depending on some other component)... and then let the user choose the relevant parameters for each component and send them to the component ngOnInit() with #Input or a service?
2) does a similar package already exist for me to leverage such functionality quicker?
Appreciate the advice and input :)
Rgds,
Wzz
Have a look at ngx-formly. Another option is ng-dynamic-forms. These libraries have dynamically configurable input elements section.
ngx-formly code sample from their demo below:
app.component.ts
import { Component } from '#angular/core';
import {FormGroup} from '#angular/forms';
import {FormlyFieldConfig} from '#ngx-formly/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
form = new FormGroup({});
model = {};
fields: FormlyFieldConfig[] = [
{
key: 'input',
type: 'input',
templateOptions: {
label: 'Input',
placeholder: 'Input placeholder',
required: true,
}
},
{
key: 'textarea',
type: 'textarea',
templateOptions: {
label: 'Textarea',
placeholder: 'Textarea placeholder',
required: true,
}
},
{
key: 'checkbox',
type: 'checkbox',
templateOptions: {
label: 'Checkbox',
}
},
{
key: 'select',
type: 'select',
templateOptions: {
label: 'Select',
placeholder: 'Select placeholder',
required: true,
options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', value: '2' },
{ label: 'Option 3', value: '3' },
]
}
},
{
key: 'radio',
type: 'radio',
templateOptions: {
label: 'Radio',
required: true,
options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', value: '2' },
]
}
}
];
onSubmit() {
if (this.form.valid) {
alert(JSON.stringify(this.model, null, 2));
}
}
}
app.component.html
<div class="header">
<img src="https://raw.githubusercontent.com/ngx-formly/ngx-formly/v5/logo.svg?sanitize=true" alt="" width="72" height="72">
<h4 class="mat-h2">Angular Formly Material</h4>
</div>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<formly-form
[form]="form"
[model]="model"
[fields]="fields">
</formly-form>
<button type="submit" color="primary" mat-raised-button>
Submit
</button>
<button type="reset" color="warn" mat-raised-button>
Reset
</button>
</form>

How to fix this ` error TS2322: Type 'Element' is not assignable to type 'HTMLLIElement' `

I want to ensure a list of exclusively <li/> will be passed to a component such that they will be displayed inside a <ul> element as rendered by the said component.
Here is my code:
const menuItems: HTMLLIElement[] = [
<li>Item 1</li>,
<li>Item 2</li>,
<li>Item 3</li>,
];
For each line of <li> inside the array, I get this error:
error TS2322: Type 'Element' is not assignable to type 'HTMLLIElement'.
I have tried an alternative way to create an array of li element
const menuItems = [
React.createElement(HTMLLIElement, {value: 'Item 1' }),
React.createElement(HTMLLIElement, {value: 'Item 2' }),
React.createElement(HTMLLIElement, {value: 'Item 3' }),
]
but it just gave a different error:
error TS2345: Argument of type '{ new (): HTMLLIElement; prototype: HTMLLIElement; }' is not assignable to parameter of type 'string | FunctionComponent<{ value: string; }> | ComponentClass<{ value: string; }, any>'.
Type '{ new (): HTMLLIElement; prototype: HTMLLIElement; }' is not assignable to type 'ComponentClass<{ value: string; }, any>'.
Type 'HTMLLIElement' is missing the following properties from type 'Component<{ value: string; }, any, any>': context, setState, forceUpdate, render, and 3 more.
How can I resolve this isse?

Resources