【问题标题】:Update parent boolean from child component in Angular 5从Angular 5中的子组件更新父布尔值
【发布时间】:2018-09-14 12:01:21
【问题描述】:

我只想在单击子组件中的按钮时更新父组件中的布尔值。我有一个基于动态 ngClass 隐藏和显示的滑出子组件。该类是根据父级的布尔值设置的。但是,当我从子项中的按钮关闭该组件时,我想更新父项中的布尔值:

父组件打字稿:

export class AppComponent implements OnInit   {

  showFlyout: boolean

  constructor() {}

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

和父 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>

子组件打字稿:

export class ActivateFlyoutComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

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

}

及子组件html:

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

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

【问题讨论】:

  • 使用@Output 装饰器和布尔类型的EventEmitter
  • 我的回答忘了更改子元素的状态。请接受君的回答。
  • @JordanBarber 直接操作 dom 不是做这种事情的正确方法,
  • @RandyCasburn,这正是我问这个问题的原因。我知道 DOM 操作是错误的方式,而我收到的答案帮助我消除了这种情况。感谢您的帮助!

标签: javascript angular typescript toggle angular-components


【解决方案1】:

像其他人提到的那样使用@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()"一样触发

【讨论】:

    【解决方案2】:

    您可以使用双向数据绑定来使其工作:

    应用组件:

    <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

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2018-07-15
      • 2019-08-27
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2021-03-25
      • 2018-09-15
      • 2017-11-23
      相关资源
      最近更新 更多