How to hide and replace a component in Angular2

15,820

Solution 1

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.

Solution 2

Typically you'd have both components in Parent A's template, but you'd use an ngIf to cause them to appear only when they're supposed to.

<button (click)="setButtonClicked(true)">Click Me</button>
<component-b *ngIf="!buttonWasClicked"></component-b>
<component-c *ngIf="buttonWasClicked"></component-c>

In Parent A's model, you'd have corresponding code to set the property:

buttonWasClicked: boolean = false;

setButtonClicked(clicked: boolean) {
    this.buttonWasClicked = clicked;
}

You may prefer to use NgSwitch instead of NgIf.

Share:
15,820
EI-01
Author by

EI-01

Updated on July 31, 2022

Comments

  • EI-01
    EI-01 almost 2 years

    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?