How to hide and replace a component in Angular2

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

+4
source share
2 answers

You can use a directive *ngIfor property to do this hidden.

Note the difference:

  • *ngIf Deletes and recreates the item:

, ngIf, , DOM, DOM.

  • hidden display: none

angular `s :

show/hide, , . ; NgIf . , .

:

@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

[hidden], : http://angularjs.blogspot.com.br/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

, .

+7

, ngIf, , .

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

Parent A :

buttonWasClicked: boolean = false;

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

NgSwitch ngIf.

+3

Source: https://habr.com/ru/post/1648304/


All Articles