An issue with the Pipe searchByType is resulting in an error stating that the property 'type' is not found on the type 'unknown'

I keep encountering a range of errors like

roperty does not exist on type 'unknown'

after running the command

ionic build --prod --release

src/app/pages/top-media/top-media.page.ts:18:16
18   templateUrl: './top-media.page.html',
                  ~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TopMediaPage.

 Error: src/app/pages/top-media/top-media.page.html:106:36 - error TS2339: Property 'type' does not exist on type 'unknown'.

106        <ng-container *ngIf="media?.type==='T'">

html

     <ion-refresher slot="fixed" (ionRefresh)="topMediaSet($event)">
            <ion-refresher-content pullingIcon="circles" refreshingSpinner="crescent" refreshingText="Refreshing...">
            </ion-refresher-content>
        </ion-refresher>
        <ion-row>
            <ion-col class="ion-text-center">
              <ion-button class="media-btn" mode="ios" color="danger" (click)="filter('V')">
                <ion-icon slot="icon-only" name="videocam-outline"></ion-icon>
              </ion-button>
            </ion-col>
      
            <ion-col class="ion-text-center">
              <ion-button class="media-btn" mode="ios" color="success" (click)="filter('A')">
                <ion-icon slot="icon-only" name="volume-high-outline"></ion-icon>
              </ion-button>
            </ion-col>
      
            <ion-col class="ion-text-center">
              <ion-button class="media-btn" mode="ios" color="tertiary" (click)="filter('T')">
                <ion-icon slot="icon-only" name="document-outline"></ion-icon>
              </ion-button>
            </ion-col>
      
            <ion-col class="ion-text-center">
              <ion-button class="media-btn" mode="ios" color="warning" (click)="filter('P')">
                <ion-icon slot="icon-only" name="camera-outline"></ion-icon>
              </ion-button>
            </ion-col>
        </ion-row>

 <ion-row *ngFor="let media of topMedia | filterByType: mediaType | slice:1;  let i = index">
  <ng-container *ngIf="media?.type==='T'">
    {{media?.message | slice:0:2000}}
</p>

The problems occur when using the custom filter I created, specifically | filterByType: mediaType

ts

topMedia:any =[];

mediaType:string = '';


constructor(
...
) { 
  this.topMediaSet();
}


topMediaSet(refresher?:any) {
this.offset = 0;
if (typeof refresher == 'undefined') {
    this.loading = true;
}
this.userData.topMedias(this.offset).pipe(
map((data: any) => {
   if (data.success) {
      this.topMedia = data.topMedia;
   }
   if (typeof refresher != 'undefined') {
            refresher.target.complete();
    }
    this.loading = false;
 })
).subscribe()
}


 filter(mediaType: string) {
  this.mediaType = mediaType;
  console.log(mediaType);
}

filter pipe

 import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterByType',
})
export class FilterByTypePipe implements PipeTransform {
/**
 * Takes a value and makes it lowercase.
 */
transform(items: any[], type: any): any {

    if (!items) return [];
    if (!type) return items;
    type = type.toLowerCase();
    console.log('type', type);
    return items.filter(it => {
        if (it.type) {
            return it.type.toLowerCase().includes(type);
        }
    });
   }
 }

I am facing an issue whenever I include

filterByType: mediaType |

If I REMOVE THIS LINE FROM NGFOR, I DON'T ENCOUNTER ANY ERRORS BUT I NEED THE FILTER. Any suggestions?

Appreciate your help

Answer №1

While this may not be the exact solution, I encourage you to try a different approach in order to troubleshoot further if needed.

Another suggestion for improvement would be to handle the filter() function on the button and update the ngFor array accordingly with a new reference.


this.mediaList = results
this.filteredMediaList = results

[...]

filter(mediaType: string) {
  this.filteredMediaList = this.mediaList.filter(item => item.type === mediaType) || [];
  this.mediaType = mediaType;
}

In your template, make sure to utilize filteredMediaList instead of mediaList

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

When using Angular version 13 alongside rxjs 7.4 and TypeScript 4+, an issue arises with the error message: "Declaration file for module 'rxjs' not found"

Currently embarking on a new Angular app using V13 and rxjs7.4, I encountered the error shown above when trying to import: import { BehaviorSubject } from 'rxjs'; Initially, I attempted to address this by creating a typings.d.ts declaration as s ...

Is there a way to access and read an Excel file stored within the assets folder using Angular?

I need assistance converting an excel file to a JSON format. My excel file is currently stored in the assets folder, and I am looking for guidance on how to access it from app.component.ts. Any help would be greatly appreciated! ...

Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions? type ProductType = { props: | { ...

Can we create a class to represent a JSON object?

Can a JSON be modeled with a class in TypeScript (or Angular)? For example, I am using Firebase and have a node called /books structured like this: books -- 157sq561sqs1 -- author: 'Foo' -- title: 'Hello world' (Where 1 ...

Converting files to base64 before uploading them in Angular

I am facing an issue with uploading files from an Angular 4 app to a JSON API service that requires base64 strings as file content. My approach involves reading the file using FileReader.readAsDataURL, and upon user confirmation for upload, I create a JSO ...

Exploring Angular 17 with the Nebular framework through the implementation of Standalone Components

Exploring Angular in combination with Nebular for UI has been my recent focus. To get started, I decided to create a quick app and dive into the intricacies of these frameworks. After setting up Angular, I initialized a new app using app new my-app. I en ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

How can I bring the toolbar to the forefront of the page in an Angular/HTML environment?

I am currently facing an issue with bringing the toolbar to the forefront of the page. When I scroll down, the elements on the page end up covering the toolbar which is not the desired behavior. Below is the CSS code for the toolbar: .maintoolbar.mat-tool ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

When intercepted, the HttpRequest is being canceled

Solution Needed for Request Cancellation Issue Encountering a problem with the usage of HttpInterceptor to include the Authorize header in all HTTP requests sent to AWS API Gateway. The issue arises as all these requests are getting cancelled when interce ...

the Sprite fails to appear on the screen

Can you help me figure out how to fix the issue I'm having with loading images in this component? Currently, when I refresh the page, the image does not load properly and appears resized to 1 pixel width. Should I wait for the image to fully load befo ...

Angular 7 and Webpack 4 combine to create a secure environment for CSS encapsulation

I find myself in a challenging situation where I have a hybrid environment consisting of both Angular 1.x and Angular 7 routes. The Angular 1.x routes rely on the older version of Bootstrap (3), while the Angular 7 routes are supposed to utilize Bootstrap ...

Tips for implementing a search filter in a select dropdown menu using Angular

I am attempting to enhance my select option list by including a search filter. With numerous options available, I believe that having a search function will make it easier for the user to locate their desired selection. I hope my message is clear despite ...

Steps to pass an injection token into a component's constructor during unit testing

In my code, I have an injection token that looks like this: export const IS_SEO_PAGE = new InjectionToken<boolean>('accommodation.seo'); I am using it in a component like this: constructor(@Inject(IS_SEO_PAGE) private isSeo: boolean, Ho ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Troubleshooting a resizing problem in Angular's ag-grid

Is there a way to enable column resizing without allowing users to resize columns to the left side and create blank spaces on the right of the grid? Please refer to the image below for clarification. https://i.sstatic.net/cnhYn.png ...

Displaying a dynamic array in Angular that shows all results, not just the data under a

Trying to grasp the complexities of Angular 5, I am faced with a challenge. The code successfully passes the "id" number from the array to the URL, but when accessing model/1, all objects from the array are displayed instead of just the object under id 1. ...

angular2 utilize rxjs to search for threads based on user input

Hey there! I'm working on creating a mini forum inspired by stackoverflow and I'm currently in the process of adding a basic text filter for thread titles. I've recently delved into rxjs and pipes, and this is what I've come up with so ...

What could be the rationale behind the optional chaining operator not being fully compatible with a union of classes in TypeScript?

Imagine I have a combination of classes: type X = ClassA | ClassB | ClassC; Both ClassA and ClassC have a shared method called methodY. Why is it that I can't simply use the optional chaining operator to call for methodY? class ClassA { methodY ...