Show the value in Angular in a dynamic way

My template needs to display the text 'Passed' only if item.name === 'michael' is not true. The component receives data in an array called courses[] from its parent. There are two interfaces, Courses and Teachers, where each course ID has associated Teacher data.

Below is the code snippet:

@Input() courses[];
isRequired = false;

ngOnInit() {
    for (const entry of this.courses) {
        this.checkData(entry);
    }
}

checkData(singleCourse: Courses): void {
    this.someService.getTeacherDetails(singleCourse.id).subscribe(item => {
        if (item.name !== 'michael') {
            this.isRequired = true;
        }
    });
}

interface Courses {
    id: number;
    name: string;
    price: number;
}

interface Teachers {
    name: string;
    address: string;
}

The variable isRequired, which sets true or false, does not seem to be functioning correctly. The method getTeacherDetails() returns an Observable<Teacher> using an HTTP request.

<tbody>
    <tr *ngFor="let course of courses">
      <td>
        {{course.name}}
      </td>
      <td>
        <span *ngIf="!isRequired"> Passed </span> // This part is not working as expected
      </td>
    </tr>
</tbody>

Answer №1

Whenever a component has a name, the isRequired flag will be automatically assigned to it.

To check if the name 'michael' is present in the listing, you can use listing.name === 'michael'.

<tbody>
    <tr *ngFor="let listing of courses">
      <td>
        {{listing.name}}
      </td>
      <td>
        <span *ngIf="listing.name === 'michael'"> Passed </span> // This part is currently not functioning properly
      </td>
</tbody>

Answer №2

Ensure that your isRequired is an observable as well.

You can set it up like this:

public isRequired$ = new ReplaySubject<boolean>(1);

In your method, do the following:

onCheckData(singleList: Courses) {
this.someService.someObservable(singleList.id).subscribe( item => {
    if (item.name === 'michael') {
        this.isRequired$.next(true);
     }
    });
   }

Remember to use the dollar sign convention for observables.

<span *ngIf="!isRequired$"> Passed </span>

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

Define the output type of an arrow function within an interface signature

How can I inform typescript that I will be utilizing an interface containing a function called "foo" which always returns a string. The implementation of the function will be specified by the object implementing the interface. For example: export interfac ...

Having trouble sending an image to the API endpoint using Angular 6 reactive form

Currently utilizing Angular 6 along with Reactive Form The task at hand involves uploading a user avatar image, which led to the creation of a change-avatar component containing the code provided below. import {Component, OnInit, ViewChild} from '@a ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...

Optionalize keys containing a specific character in their name

Imagine I have an object similar to the following: const obj = { a: 1, "b?": 2, "c?": 3 } The current type of this object is as follows: type Obj = { a: number; "b?": number; "c?": number; } Is there a ...

Having trouble disabling an ESLint rule for ESLint, TypeScript, Vue, and WebPack Encore?

I've been delving into Webpack Encore and ESLint issues for quite some time now, but unfortunately, I haven't been able to find a solution to my problem. Specifically, I've been trying to change or disable certain TypeScript-ESLint rules, b ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

Bringing in AuthError with TypeScript from Firebase

Is it possible to verify if an error is of type "AuthError" in TypeScript when using Firebase? I have a Https Callable function with a try/catch block that looks like this: try { await admin.auth().getUser(data.uid); // will throw error if user doesn& ...

Having trouble with ng-repeat in AngularJS after including Angular 17 web components to index.html?

<select ng-if="!isOtherRemarkSelected" class="form-control m-1" ng-model="selectedRemark.value" ng-change="handleRemarks()"> <option value="">Select Remarks</option> <op ...

Retrieve your Docusign Access Code using the typescript httpClient.post method

I am currently struggling to obtain the access token through the Docusign API. My code is producing an error in Xcode and I am unable to make it work on my native device or browser, despite successfully testing it via Postman. When attempting to run it in ...

Issues arise with Typescript compiler on Windows systems due to soft symlinks causing compilation failures

In my TypeScript project, symlinks function properly on both macOS and Linux. However, when executing tsc in git-bash on Windows (not within WSL), the files cannot be resolved by tsc. ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Utilizing custom colors in a Typescript/React/MUI Button component to enhance its design

How can I apply custom colors to the Button component without getting an error? Are there any possible solutions for this issue? I followed the module augmentation approach outlined in the documentation, but the problem persists: https://mui.com/material ...

How to Retrieve ViewChild Element from within Input Component in Angular 2

Currently, I am utilizing ViewChild to target a specific HTML element within an Angular 2 component. My goal is to access this element from an Input field, but I am struggling with the correct syntax to correctly target the element in question. Below is th ...

Issues with Tagged Union Types in Visual Studio Code

Currently, I am working on implementing a tagged union type pattern for my action creators within a redux application. The TypeScript compiles without any issues, however, my code editor, Visual Studio Code 1.26.1, is flagging an error. [ts] Type &ap ...

Issue with React Context Provider failing to set value

I am currently diving into React context hooks and encountering an issue that is puzzling me. I have established a user context with the simple string message of "hello user" as follows: import { useContext, createContext } from "react" export ...

Perform TypeScript type checks exclusively on a Next.js project

In my current project using Next.js with TypeScript in a mono-repo setup, I have multiple applications under the same repository. When pushing changes to this setup, various hooks are triggered locally to ensure that the modifications meet the required sta ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

Error: Property 'mytest' is undefined and cannot be read

While working with Swagger API, I encountered an error message when calling the endpoint stating "Cannot read property 'mytest' of undefined" class UserData { private mytest(req:any, res:any, next:any){ return res.json('test32423423&a ...

The upcoming developer manages to execute the program successfully, however, it continues to load indefinitely

Executing the command yarn dev consistently runs successfully in my VS Code terminal: $ yarn dev yarn run v1.22.19 warning ..\..\..\..\package.json: No license field $ next dev ready - started server on 0.0.0.0:3000, url: http://localho ...