joff
joff

Reputation: 23

hidding button of another view angular2

hello dears geek i have a problem with angular2: I'm developing an application in angular2

(menuComponent, menuView.html)
(listProductComponent, listProductView.html)
(detailProductComponent, detailProductView.html)

i have a button in the menuView.html for add new Product like this

<ul class="nav nav-tabs">
    <li><a class="active" [routerLink]="['ListeProduct']">Product</a></li>
    <li><a [routerLink]="['ListeArticle']">Articles</a></li>
    <li><a [routerLink]="['ListeClients']">Clients</a></li>   
</ul>
<button  type="button" (click)="Add()" class="btn btn-primary    ajouter">Add</button>`  

my listProductView.html is:

<table class="table table-striped">
     <thead>
      <tr>
        <th>Code Product</th>
        <th>Product Name</th>
        <th>Cost</th>
    </tr>
</thead>
    <tr *ngFor="#product of products" >
        <td>{{product.code}}</td>
        <td>{{product.name}}</td>
        <td>{{product.cost}}</td>
    </tr>   
</table> `

what I need is when I click on one product of the listProduct to see the product detail in detailProductView.html is to hide the button Add from menuView.html.

Upvotes: 2

Views: 1441

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

I think that you could leverage a shared service with an EventEmitter property. One component will emit an event based on it and this other component will be notified by subscribing the EventEmitter. When the event is received, this component can set a property used to show / hide the button...

  • Shared service

    @Injectable()
    export class MenuService {
      addButtonEvent: EventEmitter = new EventEmitter();
    }
    

    Don't forget to define the corresponding provider in the boostrap function to be able to share the same instance of the service for the whole application: `bootstrap(App, [ MenuService ]);

  • MenuComponent component

    @Component({ ... })
    export class MenuComponent {
      showAdd: boolean = false;
      constructor(menuService: MenuService) {
        menuService.addButtonEvent.subscribe(
          (showAdd) => {
            this.showAdd = !this.showAdd;
          }
       );
     }
    

    }

  • ProductListComponent component:

    export class ProductListComponent {
      constructor(private service: MenuService) {
      }
    
      toggleAddButton():void {
        this.addButton = this.addButton;
        this.service.addButtonEvent.emit(this.addButton);
      }
    }
    

See this question for more details of the implementation of this approach:

Upvotes: 2

Related Questions