问题描述
您好,我有一个父级组件(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?
推荐答案
为此,您可以使用 * ngIf
指令或 hidden
属性.
To do that you can use the *ngIf
directive or the hidden
property.
请注意区别:
-
* ngIf
删除并重新创建元素:
*ngIf
removes and recreates the element:
-
hidden
使用display隐藏元素:无
从angular的文档:
检查以下示例:
@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
为进一步了解 [hidden]
,我指出了这篇文章: http://angularjs.blogspot.com.br/2016/04/5-rookie-mistakes-to-avoid-with-angular.html
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中隐藏和替换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!