简体   繁体   中英

How to create input type text dynamically in typescript

I know in javascript, I can create an element in below way.

     var input = document.createElement("input");
     input.type = "text";
     input.className = "css-class-name"; // set the CSS class
     document.body.appendChild(input);

In my angular application, I'm getting some array value from http service inside ngOnInit of app.component.ts.

I have a scenario to create the input type text dynamically based on array value. If the array value is 5, it should create five input type.

Is it possible with typescript? Or should I use the above code in typescript as well?

What is the best approach to deal this scenario?

Create a bundle of form controls. Stackblitz

inputs: FormControl[] = [];

ngOnInit() {
  this.myService.getNumberOfInputs().subscribe(count => {
    for (let i = 0; i < count; i++) {
      this.inputs.push(new FormControl(''));
    }
  });
}
<input type="text" *ngFor="let input of inputs" [formControl]="input">

Use the *ngFor , which is an Angular directive, to loop over elements of the array. If in your model you have public array = [1, 2, 3, 4] , and in your template you have

<ul>
  <li *ngFor="let element of array">{{ element }}</li>
</ul>

this will print the following DOM:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

So, for your problem, to create inputs, just put inputs inside the loop.

<div *ngFor="let element of array">
  <input type="text" class="css-class-name">
</div>

By the way, this is a basic operation in Angular templates. I urge you to read the official introduction to Angular from the official site to get a grasp at what Angular can do.

Component:

public inputControlsArr : Array<any> = [];

this.service.getValues().subscribe((values)=>{
   this.inputControlsArr = values;
});

Template:

<div *ngFor="let input of inputControlsArr; let i = index;">
    <input type="text" [(ngModel)}="inputControlsArr[i]"/>
</div>

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