Eric
Eric

Reputation: 1

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.

Upvotes: 0

Views: 9518

Answers (2)

Eric
Eric

Reputation: 1

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

Upvotes: 0

yazan
yazan

Reputation: 537

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

Upvotes: 4

Related Questions