如何在Angular2中隐藏和替换组件 [英] How to hide and replace a component in Angular2
问题描述
您好,我有一个父级组件(A),并且有2个子级组件(B和C).父级A默认情况下显示子组件B.现在,当单击父级A上显示的按钮时,它将用子组件C替换子组件B.在angular2中单击按钮后,如何用组件C替换组件B?/p>
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?
推荐答案
To do that you can use the *ngIf
directive or the hidden
property.
请注意区别:
-
* ngIf
删除并重新创建元素:
*ngIf
removes and recreates the element:
如果分配给ngIf的表达式的计算结果为假值,则元素已从DOM中删除,否则该元素的克隆为重新插入DOM.
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
使用display隐藏元素:无
从angular的文档:
显示/隐藏技术对于小型元素树可能很好.我们隐藏大树时应保持警惕;NgIf可能是更安全的选择.在得出结论之前,务必先进行测量.
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.
检查以下示例:
@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;
}
}
柱塞: 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
希望有帮助.
这篇关于如何在Angular2中隐藏和替换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!