简体   繁体   中英

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.

You can use ngModel to bind your selection from the "select" and display it in the input by binding also.

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:

  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.

And the selectedLevel will be used for initalizing the first selected value for the dropdown and the input element using angular binding.

StackBlitz

You can see code here : 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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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