checkbox - Angular 5根据条件禁用和启用复选框

标签 checkbox angular5

我正在尝试实现一个验证,如果用户输入的特定值与从服务返回的值匹配,我想禁用该按钮,下面是我的代码:

在组件中,我调用返回用户名的服务,如下所示,这是(UserNames)的控制台日志:

0:{Name: "John", userId: "23432"}
1:{Name: "Smith", userId: "12323"}
2:{Name: "Alan", userId: "5223"}
3:{Name: "Jenny", userId: "124"}

在模板中,我使用 NgFor 来迭代用户名,如下所示

    <div *ngFor="let id of UserNames let i = index;">  
    <input type="radio" name="radio" [checked]="UserNames.userid" (click)="Submit(UserInput)"> <span>Submit</span>
  </div>

我想要实现的是,如果我输入 23432,按钮应该被禁用,因为服务已经返回带有该值的 userId,除非输入了新的用户 ID,按钮应该被启用。

最佳答案

因此,按照您所描述的方式禁用提交按钮的一般情况如下所示:

<button type="submit" [disabled]="someValidationFn()" ...>

someValidationFn()根据您描述的用例,将包含类似

return UserNames.find(name => { return name.userId === userInput;})) ;

哪里userInput是组件中绑定(bind)到某些用户输入值的单独属性,可能是通过像

这样的开放文本输入

<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">

但是,从您粘贴的标记片段*来看,我不清楚您是否将“文本”输入与单选按钮组分开。如果单选按钮组旨在将提交操作附加到其各个按钮(不应该),那么您实际上可以保证用户选择将包含 UserNames 中存在的 userId数组:您提供的唯一输入基于最初来自您的服务的数据。

根据您描述的用例,我不确定为什么您会有单选按钮组。听起来您只需要带有验证方法的文本输入字段,以确保 UserNames 中不存在用户输入。 。

因为我在那里写了一堆抽象片段,所以我认为展示一些基本的 html 和 js 可能会有所帮助,我将它们放在一起:

// html
<form submit="someSubmitAction()">
  <input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
  <button type="submit" [disabled]="someValidationFn()">Submit</button>
</form>

// js
/* don't forget your @Component annotation and class declaration -- I'm assuming these exist and are correct. The class definition encloses all the following logic. */
public userInput: string;
public UserNames: any[];
/* then some service method which grabs the existing UserNames on component's construction or initialization and stores them in UserNames */
public someValidationFn() {
    return UserNames.find(name => { return name.userId === userInput;}));
}
public someSubmitAction() { 
    /* presumably some other service method which POSTs the data */
}

*说到您粘贴的代码片段,有几个错误: *ngFor="let id of UserNames <-- 你不会通过引用 UserNames 来获得 id数组在这里;您将获得 UserNames 的成员每次迭代中的数组 - 即,您会得到 {Name: "John", userId: "23432"} ,然后{Name: "Smith", userId: "12323"} , 等等。这不一定是错误,但我假设,b/c 你使用了 id作为变量名,您期望的只是 userId field 。否则你必须使用{{id.userId}}在每次迭代中访问实际的 id。 bob.mazzo 提到了使用 [checked] 的另一个问题。属性

关于checkbox - Angular 5根据条件禁用和启用复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51274467/

相关文章:

javascript - 将复选框选中的值传递给脚本变量

angular5 - mat-select 所需的验证不起作用

css - <div (click) ="handler()"> 在 edge 中不起作用,但在 IE11 和其他浏览器中起作用

arrays - Angular 5 array.filter 内未定义

javascript - 具有多个条件的 if 语句不起作用

Angular模板绑定(bind),多次调用回调函数

javascript - 使用 getElementById( x ).onclick = someFunction

c# - 如何在 WPF C# 应用程序中动态添加复选框

javascript - 使用 jQuery 单击多个复选框

r - 在 Shiny 应用程序中对齐多列中的复选框元素