简体   繁体   English

如何在打字稿中动态创建输入文字

[英]How to create input type text dynamically in typescript

I know in javascript, I can create an element in below way. 我知道在javascript中,我可以按以下方式创建元素。

     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. 在我的角度应用程序中,我从ngOnInit的ngOnInit中的http服务获取了一些数组值。

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. 如果数组值为5,则应创建五个输入类型。

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 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. 使用*ngFor (这是一个Angular指令)来遍历数组的元素。 If in your model you have public array = [1, 2, 3, 4] , and in your template you have 如果在模型中您有public array = [1, 2, 3, 4] ,在模板中您有

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

this will print the following DOM: 这将打印以下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. 顺便说一下,这是Angular模板中的基本操作。 I urge you to read the official introduction to Angular from the official site to get a grasp at what Angular can do. 我敦促您从官方站点阅读Angular的官方介绍,以了解Angular可以做什么。

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>

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

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