How to hide and replace a component in Angular2

EI-01 picture EI-01 · Jul 19, 2016 · Viewed 15.6k times · Source

Hello i have a parent component (A) and it has 2 child components (B and C). Parent A by default displays child component B. Now when a button is clicked that is displayed on parent A, it replaces child component B with child component C. How can i replace component B with Component C after the button is clicked in angular2?

Answer

Alexandre Junges picture Alexandre Junges · Jul 19, 2016

To do that you can use the *ngIf directive or the hidden property.

Note the difference:

  • *ngIf removes and recreates the element:

If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

  • hidden hides the element using display: none

From angular`s documentation:

The show/hide technique is probably fine for small element trees. We should be wary when hiding large trees; NgIf may be the safer choice. Always measure before leaping to conclusions.

Check the example below:

@Component({
  selector: 'my-app',
  template: `
    <b>Using *ngIf:</b>
    <div *ngIf="!isOn">Light Off</div>
    <div *ngIf="isOn">Light On</div>
    <br />
    <b>Using [hidden]:</b>
    <div [hidden]="isOn">Light Off</div>
    <div [hidden]="!isOn">Light On</div>
    <br />
    <button (click)="setState()">{{ getButtonText() }}</button>
  `
})
export class AppComponent {

  private isOn: boolean = false;

  getButtonText(): string {
    return `Switch ${ this.isOn ? 'Off' : 'On' }`;
  }
  setState(): void {
    this.isOn = !this.isOn;
  }

}

Plunker: http://plnkr.co/edit/7b1eWgSHiM1QV6vDUAB0

For further reading about [hidden], I indicate this article: http://angularjs.blogspot.com.br/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

Hope that helps.