1

I have a component defined "FancyButton". I have it here in the template:

...
<div class="container">
  <div class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="removeFancyButton">Remove</button>
  <button (click)="addFancyButton">Add</button>
</div>
...

My question is, How can I programatically remove:

  <div class="fancy">
    <fancybutton></fancybutton>
  </div>

When I click on the remove button? Conversely, how do I add it back in? I would like it to trigger ngOnDestroy if possible, and if its "re-added", trigger ngOnInit when added back in.

This is my fancy-button component, below is the parent template that i have the fancy-button integrated in within the home.component.html:

@Component({
  selector: 'fancy-button',
  template: `<button>clickme</button>`
})
export class FancyButton {}

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
Rolando
  • 58,640
  • 98
  • 266
  • 407

4 Answers4

6

Give *ngIf a try, it removes the dom element when it isn't supposed to be shown and conversely adds the dom element when it is

Removes or recreates a portion of the DOM tree based on an {expression}.

...
<div class="container">
  <div *ngIf="showButton" class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="removeFancyButton">Remove</button>
  <button (click)="addFancyButton">Add</button>
</div>
...

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html',
  directives: [FancyButton],
})
export class Home {
    showButton: Boolean = true;

    addFancyButton() {
        // Do everything you need to
        this.showButton = true;
    }
    removeFancyButton() {
        // Do everything you need to
        this.showButton = false;
    }
}
Logan H
  • 3,383
  • 2
  • 33
  • 50
0

declare some component property like isFancyBtnVisible = true and change it on click. Then use *ngIf="isFancyBtnVisible" on your button component

Yaroslav Grishajev
  • 2,127
  • 17
  • 22
0

If you use *ngIf it will call ngOnOnit when true and ngOnDestroy when false.

<fancy-button *ngIf="showButton"></fancy-button>

silentsod
  • 8,165
  • 42
  • 40
0

You can only remove components imperatively that were added imperatively. For an example see Angular 2 dynamic tabs with user-click chosen components. Otherwise use *ngIf="expr". If the expression is false, the content is removed.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567