此处,要求是从showbtnContent()
点击app.component.html
时,两个div = id =' btn1Content'和id =' btn2Content' child.component.html
应切换。这里传递了选择器<app-child></app-child>
app.component.html
。即当点击btn1时div id =&#39; btn1Content&#39;应该显示和div id =&#39; btn2Content&#39;应该隐藏,反之亦然。
app.component.html
----------------------
<button class='btn' (click)="showbtnContent('btn1');">btn1</btn>
<button class='btn' (click)="showbtnContent('btn2');">btn2</btn>
<app-child></app-child>
app.component.ts
-------------------
showbtnContent(btn){
if(btn === 'btn1'){
thisbtnContent = true;
}else{
thisbtnContent = false;
}
}
child.component.html
-------------------
<div *ngIf='thisbtnContent' id='btn1Content'>jjjjjjjjjjjjjjjjjj</div>
<div *ngIf='!thisbtnContent id='btn2Content'>jjjjjjjjjjjjjjjjjj</div>
child.component.ts
------------------------
@Component({
selector: 'app-child'
});
thisbtnContent = true;
答案 0 :(得分:0)
您需要将数据从父app.component
传递给子组件,以便孩子明白它将切换。
在子组件中声明@Input
类型变量,它将从父组件输入并切换
app.component.html
----------------------
<button class='btn' (click)="showbtnContent('btn1');">btn1</btn>
<button class='btn' (click)="showbtnContent('btn2');">btn2</btn>
<app-child></app-child>
app.component.ts
-------------------
showbtnContent(btn){
if(btn === 'btn1'){
thisbtnContent = true;
}else{
thisbtnContent = false;
}
}
现在,您希望将thisbtnContent
传递给子传递,同时调用子组件,如下所示
<child1 [toggle]="thisbtnContent"></child1>
现在,子组件应该在子组件中捕获toggle
为@Input
。
child.component.html
-------------------
<div *ngIf='toggle' id='btn1Content'>jjjjjjjjjjjjjjjjjj</div>
<div *ngIf='!toggle' id='btn2Content'>jjjjjjjjjjjjjjjjjj</div>
child.component.ts
------------------------
@Component({
selector: 'app-child'
});
@Input() toggle;