【问题标题】:component cross communication using button使用按钮的组件交叉通信
【发布时间】:2020-09-27 21:23:26
【问题描述】:

原始行为:单击按钮时,它会切换 div(关闭以打开,打开以关闭) ChildComponent.html

<div *ngIf="showFiller" class="sidenav">
<p>Hey</p>
</div>

<div class="content">
  <button (click)="showFiller = !showFiller" mat-raised-button>
    Toggle extra text
  </button>
  <p> Hello </p>
</div>

子组件.ts

showFiller = false;

请求:现在我需要将按钮移动到父组件,但在子组件中需要相同的行为。所以按钮应该在父级中,动作应该在子级中表示 这是我试过的代码

父组件.html

<mat-icon mat-button (click)="toggle()" class="index">menu</mat-icon>

父组件.ts

show: boolean = true;
  toggle(){
    this.show = !this.show;
    this.show;
    console.log(this.show);
  }

子组件.html

<div *ngIf="showFiller" class="sidenav">
<p>Hey</p>
</div>

<div class="content">
  <!-- <button (click)="showFiller = !showFiller" mat-raised-button>
    Toggle extra text
  </button> -->
  <p> Hello </p>
</div>

子组件.ts

@Input() show: boolean;
  showFiller: boolean = true;
  ngOnInit(): void {
    this.showFiller = this.show;
    console.log(this.showFiller);
  }

  ngOnChanges(changes: boolean) {
    this.showFiller = this.show;
    console.log(this.showFiller);
  }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您在子组件中保留了另一个不必要的状态。您的父组件确定状态并将其传递给您的子组件。子组件的任务只是根据输入显示/隐藏 div。

    例如https://stackblitz.com/edit/angular-ivy-4pff9m

    【讨论】:

    • 您好,感谢您的支持,我在此处进行了建议的更改 [stackblitz.com/edit/…,但是在一个组件中单击的按钮不会反映在第二个组件中
    • 那么你必须将 show 变量传递给你的子组件,并且你在你的子组件中再次复制状态(show 和 showFiller 变量)。只需要 1 个布尔值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多