【问题标题】:How to change input label dynamically in Angular?如何在Angular中动态更改输入标签?
【发布时间】:2021-02-15 02:56:49
【问题描述】:

我有两个输入的表单。第一个是“选择”,第二个是“输入”。

我使用 Angular,我想做的是第二个输入的文本标签会根据我在第一个输入上的选择而变化。

【问题讨论】:

  • 请分享一个代码示例。

标签: angular forms input label


【解决方案1】:

您可以使用 ngModel 从“选择”中绑定您的选择,并通过绑定将其显示在输入中。

假设我们有如下选择和输入:

<select type="number" [(ngModel)]="selectedLevel">
      <option *ngFor="let level of levels" [ngValue]="level">{{level}}</option>
    </select>
<input value="{{selectedLevel}}">

在你的 ts 文件中:

  levels = ["AA", "BB"];
  selectedLevel = this.levels[0];

正如您在上面看到的那样,levels 将用于使用 ngFor 为下拉菜单添加值。

并且 selectedLevel 将用于初始化下拉列表的第一个选定值和使用角度绑定的输入元素。

StackBlitz

【讨论】:

    【解决方案2】:

    您可以在此处查看代码:https://stackblitz.com/edit/angular-ivy-rvspsy?file=src/app/app.component.ts

    我想要的是“评论”文本标签会根据我在第一个输入中选择的内容而变化。

    <form [formGroup]="orderForm" (ngSubmit)="makeOrder()">
    
        <label for="order_type">Type</label>&nbsp;
        <select
        formControlName="order_type"
        id="order_type"
        placeholder="Type"
        (change)="changes()">
        <option value="">Choose</option>
        <option
          *ngFor="let orderType of orderTypes"
          [value]="orderType">
          {{ orderType }}
        </option>
      </select>
    
        <br /><br />
    
        <label for="comment">Comment</label>&nbsp;
        <input
          type="text"
          formControlName="comment"
          id="comment"
          placeholder="Comment"
          autocomplete="off">
    
    </form>

    orderForm: FormGroup;
      orderTypes = ["Buy", "Sell"];
    
      constructor(private fb: FormBuilder) {}
    
      ngOnInit(): void {
        this.orderForm = this.fb.group({
          order_type: [""],
          comment: [""]
        });
      }
    
      changes(): void {}
    
      makeOrder(): void {
        const form = this.orderForm.value;
        console.log(form);
      }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 2021-12-02
      • 1970-01-01
      相关资源
      最近更新 更多