Андрей
Андрей

Reputation: 73

How add new <input> when the last input has a value?

I started to make a form - stackblitz, but I do not know how to proceed further

I want to make the same effect as here: RESTer addons shown in the picture implemented as follows: github - RESTer

I tried with the method (change) but it works after pressing Enter, that does not suit me

Upvotes: 2

Views: 83

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73751

You can handle the input event on the last line:

<div *ngFor="let header of headers; let i = index; let isLast = last" fxLayout="row" fxLayoutGap="25px">
  <mat-form-field fxFlex="25">
    <input matInput placeholder="Name" type="text" name="name-{{i}}" value="{{header.name}}" 
           (input)="addInput(isLast)">
  </mat-form-field>
  <mat-form-field fxFlex>
    <input matInput placeholder="Value" type="text" name="value-{{i}}" value="{{header.value}}">
  </mat-form-field>
  ...
</div>

with the addInput method, which adds a new record the first time the input content changes:

export class DynamicformComponent implements OnInit {

  public headers: any[] = [];

  ngOnInit() {
    this.headers = [
      { name: 'Accept-Encoding', value: 'gzip' },
      { name: 'Accept-Charset', value: 'utf-8' },
      { name: 'User-Agent', value: '' },
      { name: 'Accept', value: 'text/plain' },
      { name: 'Cookie', value: '' },
      { name: '', value: '' }
    ];
  }

  addInput(isLast: boolean) {
    if (isLast) {
      this.headers.push({ name: '', value: '' });
    }
  }

  removeInput(index) {
    this.headers.splice(index, 1)
  }
}

See this stackblitz for a demo.

Upvotes: 2

wFitz
wFitz

Reputation: 1286

You could use formArray, if you use reactive forms. have a look at https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

Upvotes: 1

Related Questions