【问题标题】:Binding dynamically changed control/getting to render on screen绑定动态更改的控件/在屏幕上呈现
【发布时间】:2021-07-17 19:53:36
【问题描述】:

我正在尝试创建一个基于有效文本框条目 (control1) 动态更改下拉列表 (control2) 的表单。当用户在文本框 (control1) 中输入值时,我希望下拉列表 (control2) 将特定字符串绑定到该值,并在下拉列表中呈现单词“日期”。下拉列表只有两个值:“选定”或“日期”,如果用户在文本框中输入错误的值,“选定”值会显示并取消下拉 (control2) 值。我无法同时显示“日期”框和“选定”框以及分别更新 control2,有人可以帮忙吗?

表单创建:

form: FormGroup = this.fb.group({
  control1: (null),
  control2: {value: null, disabled: true}
})

检查有效的文本框条目:

validControl(): boolean {
  if(this.control1.value !== null && this.control1.value !== ''
&& this.control1.valid) {
    return true;
}
else {
  return false;
}

这是一个stackblitz demo,它也显示了前端:

简而言之,这就是我要找的东西:

  • 用户在文本框 (control1) 中键入有效条目
  • 下拉菜单显示“日期”并将“EDTEV”绑定到 control2
  • 如果用户删除了 control1 中的文本,则下拉菜单显示“已选择”并取消 control2 中的值

【问题讨论】:

  • control3 是从哪里来的?您只描述了 control1 和 control2,但在您的演示中您使用的是 control1 和 control3

标签: angular typescript angular-reactive-forms


【解决方案1】:

根据我对这个问题的理解,这可能会有所帮助:

  1. 在 *ngIf 条件下将 control3 修改为 control1
  2. 修改 *ngIf 条件检查位(当没有值和 输入内容时,您可以根据您的要求进行更改)

只修改了app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<form [formGroup]="form">
  <input type="text" formControlName="control1"><br><br>
  <select formControlName="control3">
    <ng-container *ngIf="form.get('control1').value">
    <option *ngFor="let items of response" [value]="items.code">{{items.description}}</option>
    </ng-container>
    <ng-container *ngIf="!form.get('control1').value">
    <option>SELECTED</option>
    </ng-container>
  </select>
</form><br>

<button (click)="test()">TEST</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2014-09-14
    • 2021-09-25
    • 2011-12-08
    • 2015-03-05
    • 2012-10-02
    • 2020-11-27
    相关资源
    最近更新 更多