When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue

The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed

A parent component named page-blog.component.html is responsible for defining the class styles and passing them to the child component called post-card.component.ts

The problem arises in the parent HTML component when attempting to set the class styling variables from the class component, specifically with the section @Input() layout: PostCardLayout;

I have temporarily resolved this issue by adjusting the

"strictInputTypes": false,
setting in the tsconfig.json file, although I acknowledge this may lead to potential errors in future development.

The child class is defined in post-card.component.ts

import { Component, HostBinding, Input } from '@angular/core';

 export type PostCardLayout = 'list' | 'grid' | 'grid-sm';

 @Component({
  selector: 'app-post-card',
   templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.scss']
 })
export class PostCardComponent {

@Input() post;

@Input() layout: PostCardLayout;

@HostBinding('class.post-card') classPostCard = true;

@HostBinding('class.post-card--layout--list') get classPostCardLayoutList(): boolean {
  return this.layout === 'list';
}

@HostBinding('class.post-card--layout--grid') get classPostCardLayoutGrid(): boolean {
  return this.layout === 'grid';
}

@HostBinding('class.post-card--layout--grid-sm') get classPostCardLayoutGridSm(): boolean {
  return this.layout === 'grid-sm';
}

constructor() { }
}

Below is the code snippet from the parent HTML component page-blog.component.html

                    <div class="posts-list__body">
                        <div *ngFor="let post of posts" class="posts-list__item">
                            <app-post-card
                                [post]="post"
                                [layout]="{
                                    classic: 'grid',
                                    list: 'list',
                                    grid: 'grid-sm'
                                }"
                            ></app-post-card>
                        </div>
                    </div>

Answer №1

You have defined the PostCardLayout to accept one of three values:

'list' | 'grid' | 'grid-sm'

It seems like you are trying to pass a JSON object:

[layout]="{
          classic: 'grid',
          list: 'list',
          grid: 'grid-sm'
      }[layout]"

Furthermore, there is an extra [layout] at the end of your input, which looks like a typo.

Based on my interpretation, with the typo and strictInputTypes turned off, your JSON may be converted into a string inadvertently.

Disabling

"strictInputTypes": false
is not recommended as it goes against one of TypeScript's core principles.

It appears that in your code, you simply want to assign one of the predefined values:

<app-post-card
      [post]="post"
      [layout]="'grid'">
</app-post-card>

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

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

When hovering over one div, both it and another div should be displayed simultaneously. The second div should continue to be displayed even when hovered over

I am looking to keep another div displayed when hovering over it - in this example, it says "hello." The div I want to remain visible is not a child element of the main div where I initiate the hover event. document.write("<base href=\"" + docum ...

Stop material button from animating when clicked

On my webpage, I have created a unique button structure using Angular Material design: <button mat-button class="library-tile-button"> <button mat-button class="edit-library-button"> <img class="edit-library-img" src="..."/> ...

When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

Below is the code for a controller that returns Line 1 as soon as the endpoint is called and then two seconds later it returns Line 2. When accessing the URL directly at http://ajax.dev/app_dev.php/v2, everything works as expected. /** * @Method({"GET"}) ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

What is the best way to display an image and text side by side within a single row in react-table?

I am trying to display an image and text side by side within a single column in a React table. I have successfully added two texts together in a single column using the code below: Header: "Name", id: "User", accessor: (d) => ...

Customizing the like button functionality for individual elements, with the ability to unlike, utilizing Angular

I am looking to implement a Like button feature that increments the counter when clicked once, and decrements it on another click. I have multiple elements with the like button and I want them to function independently from each other. Please note that ...

transferring data between react components

I am currently working on breaking down code into smaller components, starting with the snippet below from Rows.jsx. I am struggling to grasp how props are passed between parent and child components. Despite reading several guides and articles, I remain un ...

Maintain the functionality of an object even when it is created using the "bind" method

I'm working with a function that has the following structure: var tempFun = function() { return 'something'; } tempFun.priority = 100; My goal is to store this function in an array and bind another object to it simultaneously, like so ...

How do I transform the date "Tue Nov 26 2019 16:00:00 GMT-0800" into the .NET JSON date format "/Date(1574812800000)/"?

I am looking to convert a date from ISO format to .NET JSON date format using JavaScript. For example, I want to change "Tue Nov 26 2019 16:00:00 GMT-0800" to "/Date(1574812800000)/". ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

How do I navigate to a different page in Vue.js HTML based on user selection?

Here is my first attempt at writing HTML code: <div class="col-md-4" > <div class="form-group label-floating"> <label class="control-label">Select No</label> <select class="form-control" v-model="or" required=""> ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

Is there a way to export all images that have been imported into a React JS file with just one export command?

In the process of developing a solitaire game using React, I have implemented a Card component that displays a card on the screen based on its suit and number. Inside the Card.js file, there are several imports for image sources, such as: import cardFrontT ...