How to hide and replace a component in Angular2

青春壹個敷衍的年華 提交于 2019-12-10 17:35:26

问题


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?


回答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.




回答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.



来源:https://stackoverflow.com/questions/38446997/how-to-hide-and-replace-a-component-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!