Angular recognizing string-array type as a string input is not correct

I am encountering a challenge with an Angular CLI component that involves working with an array of strings called "searchResult":

export class ParentComponent implements OnInit {

  mockArray: string[] = [];
  searchString: string = '';
  searchResult: string[] = [];

  constructor(private service: SomeService) {
  }

  ngOnInit(): void {
    this.mockArray = this.service.getArray();
  }

  onKeyDown() {
    if (this.searchString.length > 2) {
      this.searchResult = this.mockArray.filter(symptom =>
        symptom.includes(this.searchString)
      )
    }
  }
}

Within this component, I am assigning the result of the filter method, executed on another string-array, to the searchResult variable. When passing this data down to a child component in its HTML template, I encounter an issue:

<child-component searchResult="{{searchResult}}"></child-component>

To receive and handle the variable in the child component, I utilize an @Input() declaration:

export class ChildComponent {

  @Input() searchResult: string[] = [];

}

Despite both variables being arrays of strings, upon running ng serve, I receive an error related to the line in the parent component's HTML template:

error TS2322: Type 'string' is not assignable to type 'string[]'

This error arises even though both variables are meant to be arrays of strings and not just single strings.

Update: Upon investigation, it appears that the filter method is returning a concatenated string of all items instead of an array. The original array "mockarray" used for the filter looks like this:

  [
    'elevated midi-chlorian count',
    'low self-esteem',
    'urge to flip a table',
    'headache',
    'sore feet',
    'loss of smell',
    'hearing voices',
    'pain in sole of the feet',
    'breathlessness',
    'shortness of breath',
    'difficulty breathing',
    'respiratory distress',
    'pain in knee',
    'stiff finger joints',
    'back pain'
  ];

Answer №1

Consider using Attribute Binding instead of relying on string interpolation:

<child-component [searchResult]="searchResult"></child-component>

Answer №2

Make sure to pass the searchResult variable to the child-component component as shown below:

<child-component [searchResult]="searchResult"></child-component>

It's also recommended to refer to the Angular documentation for more information:

https://angular.io/guide/inputs-outputs

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

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Inquiry regarding the implementation of DTO within a service layer parameter

I have a query regarding the choice of service layer to use. // 1 export class SomeService{ async create(dto:CreateSomeDto) {} } or // 2 export class SomeService{ async create(title: string, content: string) {} } It appears that most individuals opt ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

Guide to capturing the response in Angular 4 using HttpInterceptor

I have an Interceptor called TokenInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(private tokenService: TokenService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<Http ...

Incorporating ng2-bootstrap into an Angular2 project with SystemJS starter template

I am attempting to integrate the ng2-bootstrap modal functionality into a component of my project that is built using the angular2-starter. Below is my systemjs.conf.js configuration: /* * This config is only used during development and build phase onl ...

Utilizing Next.js to Import a Function from a Path Stored within an Environment Variable

I'm having trouble importing a function whose path is stored in an environment variable Current import statement: import { debug } from '../lib/site-A/utils' Expected import statement: import { debug } from process.env.DEBUG_PATH In my ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Unable to locate the module '@vitejs/plugin-react' or its associated type

After creating the project with npm create vite@latest and selecting ts-react, everything seemed to work fine when I ran npm run dev. However, in my vs code editor, I encountered the error message "Cannot find module '@vitejs/plugin-react' or its ...

The form data consistently replaces existing values with each new entry added

I am struggling to persist all the form values that are entered in my component using local storage. Despite setting and pushing the form values, I noticed that each time I push the data, it replaces the previously entered form data. My goal is to retain a ...

Angular: Exploring Directives - The Impact of Passing "null" versus an Empty String to the @Input Setter

I've observed an interesting behavior with the @Input setter in a Directive. It seems that when an empty string ("") is passed in the template, the setter method is not initially called. However, if the value "null" or "false" is provided, then the se ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Utilize only the necessary components from firebase-admin in Cloud Functions with Typescript

When I looked at my transpiled code from cloud functions, I noticed the following TypeScript import: import { auth, firestore } from 'firebase-admin'; It gets transpiled to: const firebase_admin_1 = require("firebase-admin"); Upon further exa ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

An error was encountered: SyntaxError - An unexpected token was found, along with one additional

I'm brand new to Angular and I'm in the process of setting up a seed-project <!DOCTYPE html> <html> <head> <title>Angular 2 Seed [using RC4] - A Basic TypeScript starter project</title> <base ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

Mastering ngClass for validation in Angular 2: Step-by-step guide

I am facing an issue with a form I have created where I applied ngclass to display an error when the form value is missing. However, the error is showing up when the form is initially loaded. It seems that by default, my input tag is invalid when the form ...

What could be the reason behind Cors preventing my API request?

Currently, I am in the process of developing a project that requires me to access an API that I have created. const endpoint = 'localhost:3000/api/v1/'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'appl ...