【问题标题】:angular 8 how to disable button of child component that use multiple times in parent componentangular 8 如何禁用在父组件中多次使用的子组件的按钮
【发布时间】:2020-06-01 03:36:55
【问题描述】:

我有一个子组件,可以在父组件中多次使用不同的操作。现在当我单击父组件中的按钮时,如何禁用子组件中存在的按钮。

我的可以多次使用的子组件:

从 'angular2/core' 导入 {Component};

@Component({
    selector: 'my-product',
    template: `<button [disabled]="isDisableButton">select</button>`
})

export class MyCardComponent {
  @Input() isDisableButton = false;
}

我的父组件html:

<div>
   <p>Product Type 1<p>
  <my-product [isDisableButton]="isDisableType1Button"></my-product>
   <button (click)="onType1()">select type 1</button>
</div>

<div>
    <p>Product  Type 2<p>
  <my-product [isDisableButton]="isDisableType2Button"></my-product>
   <button (click)="onType2()">select type 1</button>
</div>

我的父组件 ts :

      @Component({
      selector: 'my-parentComponent',
      templateUrl: '..'
    })
    export class PopupDirective {

        isDisableType1Button : boolean;
        isDisableType2Button: boolean;

     onType2(){
        this.isDisableType1Button = true;
        this.isDisableType2Button = false;
         }

    onType1(){
       this.isDisableType2Button = true;
       this.isDisableType1Button = false;
      }

  }

此解决方案无法正常工作

【问题讨论】:

  • 你能提供stack-blitz链接吗?

标签: angular angular8


【解决方案1】:

正如您在 Stackblitz 上看到的,您实现的逻辑没有任何问题。

也许您在子组件上错过了 Input 装饰器的导入:

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

【讨论】:

  • 那你能弄清楚为什么它不起作用吗?正如您在 Stackblitz 上看到的那样,这运行良好。
【解决方案2】:

您可以使用组件输出事件来做到这一点,您可以在docs 中阅读。

下面是一个非常简洁的示例以保持简洁:

<button (click)="b.disabled = true">trigger component</button>
<button #b>react on trigger</button>

触发按钮(作为您的父组件)具有点击事件的标准输出。 (内联)事件处理程序采用模板引用 (#b) 来直接操作禁用状态。

如果将其转换为示例,则应使用EventEmitter 实现输出。

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2017-11-15
    • 2021-06-04
    • 2020-11-11
    • 1970-01-01
    • 2020-03-26
    • 2021-07-13
    • 2021-05-20
    • 2021-10-05
    相关资源
    最近更新 更多