Hiding or showing a div in an Angular 6 component using a service-triggered function

After creating a service with a method that performs an action, the next step is to have this service interact with a specific component.

service.ts:

doSomething() {
    // Carries out a task here
}

In this case, the target component is described below:

myComponent.ts

The HTML file associated with myComponent contains a div element:

<div class="myDiv">Content Here</div>

The objective now is to display and hide this div element based on code within the doSomething() method of the service.

For example:

doSomething() {

    1. Display myDiv   
    2. // Perform a task here
    3. Hide myDiv
}

Is there a way to achieve this functionality?

Answer №1

Particularly, I included in the doSomething() method a flag value to control the visibility of a div.

SECTION

doSomething() {
  service
    .doSomething()
    .subscribe(
       r => {
          this.show = true;   
          2. // Perform some actions here
          this.show = false;  
       }
    );
}

<div *ngIf="show" class="myDiv">Content Goes Here</div>

However, it is crucial for this code to remain within the component and not in the service.

Answer №2

To incorporate conditional rendering, include the ngIf attribute in your HTML:

*ngIf="IAmDoingSomething" 

Inside the component file, make the necessary adjustments as shown below:

export class MyDoSomethingComponent{
public IAmDoingSomething = false;
...
   executeActions = async  () => {
       this.IAmDoingSomething = true;
       await doSomething();
       this.IAmDoingSomething = false;
    }
...
}

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

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Getting an Observable for data retrieved from a Firestore query in Angular 7

One of the methods in my service aims to return an Observable of the User object. Below is the code snippet I have written: constructor(private firestore: AngularFirestore, private db: AngularFireDatabase) { } /** * Retrieve user based on provid ...

Angular 6 offers a versatile multi-select dropdown feature

Looking to select multiple values in Angular 6 using checkboxes. When selecting a department from the dropdown, a list of employees related to that department is displayed in another dropdown with checkboxes. However, only the last value of the array app ...

Inconsistency in updating RxJS Observable item within an Observable list

I am working with an observable list of items that are manually set through a subject by calling next. However, I have noticed that when the data in the observable list is updated to include a filtered item, the corresponding observable item is not being ...

Trouble with badge generation - angular2-mdl version 4.0.1 (Angular 4)

I have been utilizing badges in the following manner: <mdl-icon [mdl-badge]="myCount" mdl-badge-overlap>some_icon</mdl-icon> Previously, with Angular 2 and an older version of mdl, when myCount:number was null, the badge would be hidden. Howe ...

Keep an eye on the output of Firebase database in Angular 2

Just starting out in angular, so please be patient :) Using Angular 2 (version 1.0.4), Angular CLI, and NodeJs 7.9. I've been trying to create a centralized service that checks if a user is logged in, retrieves their data, and sends it back for the ...

The index type '{id:number, name:string}' is not compatible for use

I am attempting to generate mock data using a custom model type that I have created. Model export class CategoryModel { /** * Properties */ public id : number; public name : string; /** * Getters */ get Id():number{ return this.id; ...

Utilize a type that is not made available for export

library is a module in Typescript that exports a specific function called someFunction. This function is designed to be called with a string input that must be one of a defined set of values. Within the library, the someFunction function is defined to onl ...

Encountering ERR_INVALID_HTTP_RESPONSE when trying to establish a connection with a Python gRPC server using @bufbuild/connect

Attempting to establish a connection to a python grpc server developed with grpcio through a web browser using connect-query. Encountering an issue where upon making a request, an ERR_INVALID_HTTP_RESPONSE error is displayed in the browser. Below is the Re ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

Can the Date class be expanded by overloading the constructor method?

In my dataset, there are dates in different formats that Typescript doesn't recognize. To address this issue, I developed a "safeDateParse" function to handle extended conversions and modified the Date.parse() method accordingly. /** Custom overload ...

Navigating routes for a module sourced from NPM: Best practices

Looking for guidance on loading Angular routes from an NPM module? Take a look at this snippet from my app.module.ts file: import { HelloWorldModule } from 'hello-world-app-npm/hello-world-app.umd.js'; // Loading module from NPM const routes = ...

Utilize generic typings to interact with the Array object

I'm facing a challenge in developing an interface that is dependent on another interface. Everything was going smoothly until I reached the Array of Objects. Let me elaborate, I have an 'Entity' that defines how a document is stored in a ...

Calculating the total sum of an array utilizing filter and reduce techniques

How can I calculate the total value of all my products in the list by adding numbers together? this.totalValue = this.items.filter((item) => item.qtyvalue) .map((item) => item.qtyvalue) .reduce ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...

`Getting Started with TypeScript in an ASP.Net MVC Application`

Due to certain reasons, we have decided to begin our project with TS rather than JS. We are facing issues with the variables set in the MVC Views, which are established by the Model of each View. For example, tes.cshtml: @model Testmodel <script> ...

Configuring Storybook to utilize typescript props with react-docgen-typescript-loader

I'm attempting to utilize react-docgen-typescript-loader for generating documentation of my props in Storybook using TypeScript Props. Unfortunately, I am facing an issue where the withInfo addon is not displaying any information. I am working with t ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

eslint warning: the use of '$localize' is flagged as an "Unsafe assignment of an `any` value"

When using $localize, eslint detects errors and returns two specific ones: Unsafe assignment of an 'any' value and Unsafe any typed template tag. It's quite strange that I seem to be the only one facing this issue while working on the proje ...