user9273032
user9273032

Reputation:

Angular 6 - Hide or Show a Div in component triggered from a Service

I have a service which has a method that does something.

service.ts:

doSomething() {
    // Does something here
}

This service talks with the component below:

myComponent.ts

I have: myComponent.html which has a div:

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

What I want to so is to show and hide the div by code in the service doSomething() method.

Like this:

doSomething() {

    1. Show myDiv   
    2. // Do something here
    3. Hide myDiv
}

How can I do this?

Upvotes: 6

Views: 44382

Answers (2)

garty
garty

Reputation: 416

Add the ngIf attribute to the markup:

*ngIf="IAmDoingSomething" 

Within the component you can do the following:

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

Upvotes: 4

Antonio de la mata
Antonio de la mata

Reputation: 404

Particulary I insert into doSomenthing() method the set of a flag value for control the div.

COMPONENT

doSomething() {
  service
    .doSomething()
    .subscribe(
       r => {
          this.show = true;   
          2. // Do something here
          this.show = false;  
       }
    );
}

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

But this code must stay into the component not in the service.

Upvotes: 6

Related Questions