当从angular2中的其他组件中的两个按钮单击时,如何从一个组件切换两个div

时间:2017-10-23 16:56:52

标签: angular

此处,要求是从showbtnContent()点击app.component.html时,两个div = id =&#39; btn1Content&#39;和id =&#39; btn2Content&#39; 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;

1 个答案:

答案 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;