【问题标题】:how to toggle two divs from one component when clicked from two buttons in other component in angular2从angular2中其他组件中的两个按钮单击时如何从一个组件切换两个div
【发布时间】:2017-10-23 16:56:52
【问题描述】:

这里,要求在app.component.html点击showbtnContent()时,child.component.html的两个div id='btn1Content'和id='btn2Content'应该切换。在这里,选择器<app-child></app-child> 被传入 app.component.html。即当 btn1 被点击时 div id='btn1Content' 应该显示并且 div id='btn2Content' 应该隐藏,反之亦然。

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;

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要将数据从父 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;
    

    【讨论】:

      猜你喜欢
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      相关资源
      最近更新 更多