【问题标题】:Angular disable button after moving away from component离开组件后的角度禁用按钮
【发布时间】:2019-04-16 14:16:10
【问题描述】:

我有一个表单和一些输入字段和一个按钮。 填写表单并单击按钮后,我打开一个包含数据表的模式(根据component1 选择的表单值。)

然后用户从这个模式中选择一些数据。一旦用户完成并关闭模式,我将显示所选值的另一个第三部分。仅供参考,我也通过我的服务存储这些选定的值。

一旦用户从我的模式中选择了一些数据,我需要禁用这个按钮,如果他们取消选择我想要启用这个按钮的数据。

如何在component1 中检查数据选择时启用/禁用此按钮(,如果数据是在模态中选择的)。因为它已经加载了,所以它不起作用。

下面是我的一些相关代码。

按钮:

 <button (click)="clicked()" type="button" [disabled]="isButtonDisabled" class="btn default">Click</button>

组件:

export class Component1 implements OnInit {
  isButtonDisabled: boolean:false;
  constructor(private myService: MyService) {}

  ngOnInit() {
    if(this.myService.getSelectedData().length>0 {
       this.isButtonDisabled = true; 
     }else{
        this.isButtonDisabled = false; 
    }
 }
}

myService 在用户进行选择或删除选择时保存数据。

this.myService.getSelectedData()

所以我认为在我的ngOnitcomponent1 中检查这个会起作用,但后来我意识到component1 已经加载了。

谁能指出这个问题的解决方案。

谢谢

【问题讨论】:

  • 不是很清楚你在问什么。您基本上想根据组件 2 中的事件禁用组件 1 中的按钮,对吗?如果是这样,您为什么不使用共享服务和主题/行为主题?
  • @Stanislasdrg 正如我在帖子中提到的,我已经在使用共享服务。我也在那里使用一个主题。但是如果我使用它,那意味着我必须在我的组件 1 中订阅它,对吧?
  • Nadhir 的解决方案是最简单的一种。否则,您确实必须订阅您的 cpt。

标签: angular


【解决方案1】:

您可以将您的服务公开如下:
constructor(public myService: MyService) {}

在您的模板中,您可以像这样直接检查函数:

[disabled]="myService.getSelectedData().length &gt; 0

你可以去掉ngOninit里面的代码

【讨论】:

    【解决方案2】:

    您可以在组件中使用ngAfterContentInit 方法。

    https://angular.io/api/core/AfterContentInit

    export class Component1 implements OnInit {
      isButtonDisabled: boolean:false;
      constructor(private myService: MyService) {}
    
      ngAfterContentInit() {
        if(this.myService.getSelectedData().length>0 {
           this.isButtonDisabled = true; 
         }else{
            this.isButtonDisabled = false; 
        }
     }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 拉斐尔这行不通。加载完所有内容后,我想启用和禁用按钮。
    猜你喜欢
    • 2017-12-14
    • 2021-08-13
    • 1970-01-01
    • 2016-08-10
    • 2017-09-17
    • 2019-02-02
    • 1970-01-01
    • 2018-11-24
    • 2019-09-20
    相关资源
    最近更新 更多