从 Angular 中的 child 组件更新 parent 布尔值 5

Update parent boolean from child component in Angular 5

我只想通过单击 child 组件中的按钮来更新 parent 组件中的布尔值。我有一个基于动态 ngClass 隐藏和显示的 slide-out child 组件。 class 是根据 parent 中的布尔值设置的。但是,当我从 child 中的按钮关闭该组件时,我想更新 parent:

中的布尔值

parent 组件打字稿:

export class AppComponent implements OnInit   {

  showFlyout: boolean

  constructor() {}

  ngOnInit() {
    this.showFlyout = false;
  }
}

和parent html:

<main>

  <button (click)="showFlyout = !showFlyout"><i class="fa fa-check"></i>Show Flyout</button>

  {{showFlyout}}

  <app-child id="flyout" [ngClass]="showFlyout ? 'active' : ''"></app-child>

</main>

child 组件打字稿:

export class ActivateFlyoutComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  closeActivationFlyout() {
    const flyout = document.getElementById('flyout');
    flyout.classList.remove('active');
  }

}

和child组件html:

<button (click)="closeFlyout()">Close</button>

这是 Stackblitz。您可以看到单击 parent 按钮可以正确切换 class 但是我如何通过单击 child 来更新该布尔值,从而使 [=33= 中不需要 closeActivationFlyout() 方法] 组件?

像其他人提到的那样使用 @Output(),但它需要发出一个事件,您还需要检查在父 html.

中触发的事件

这是一个有效的 StackBlitz

在子组件中。

@Output() onCloseClick = new EventEmitter();

closeFlyout() {
  this.onCloseClick.emit();
}

并且在父组件中html。

<app-child id="flyout" [ngClass]="showFlyout ? 'active' : ''" (onCloseClick)="showFlyout = false"></app-child>

你也可以在父组件中创建一个函数,然后触发它 (onCloseClick)="doFunction()"

您可以使用 two-way 数据绑定使其工作:

应用程序组件:

<app-child id="flyout" [(showFlyoutModel)]="showFlyout" [ngClass]="showFlyout ? 'active' : ''"></app-child>

子组件:

   import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html'
    })
    export class ChildComponent implements OnInit {
      @Input()
      showFlyoutModel;

      @Output()
      showFlyoutModelChange = new EventEmitter<boolean>();
      constructor() { }

      ngOnInit() {
      }

      closeFlyout() {
        this.showFlyoutModelChange.emit(!this.showFlyoutModel);
      }

    }

https://stackblitz.com/edit/angular-v95emc?file=app%2Fchild-component%2Fchild.component.ts