简体   繁体   English

如何在 Angular 中动态更改输入标签?

[英]How to change input label dynamically in Angular?

I have form with two inputs.我有两个输入的表单。 The first one is a "select" and the second one is "input".第一个是“选择”,第二个是“输入”。

I use Angular and what I want to do is that the text label of the second input changes depending on what I choose on the first one.我使用 Angular,我想要做的是第二个输入的文本标签会根据我在第一个输入上的选择而变化。

You can use ngModel to bind your selection from the "select" and display it in the input by binding also.您可以使用 ngModel 从“选择”绑定您的选择,并通过绑定将其显示在输入中。

Assume we have the following select and an input as follows:假设我们有以下选择和输入如下:

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

and in your ts file:并在您的 ts 文件中:

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

As you can see above that levels will be used to add the value for the dropdown using ngFor.正如您在上面看到的,级别将用于使用 ngFor 添加下拉列表的值。

And the selectedLevel will be used for initalizing the first selected value for the dropdown and the input element using angular binding. selectedLevel 将用于初始化下拉列表的第一个选定值和使用角度绑定的输入元素。

StackBlitz 闪电战

You can see code here : https://stackblitz.com/edit/angular-ivy-rvspsy?file=src/app/app.component.ts你可以在这里看到代码: https : //stackblitz.com/edit/angular-ivy-rvspsy?file=src/app/app.component.ts

What I want is that the "Comment" text label changes depending on what I choose on the first input.我想要的是“评论”文本标签根据我在第一个输入中选择的内容而变化。

 <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); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM