簡體   English   中英

如何在打字稿中動態創建輸入文字

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

我知道在javascript中,我可以按以下方式創建元素。

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

在我的角度應用程序中,我從ngOnInit的ngOnInit中的http服務獲取了一些數組值。

我有一個方案可以根據數組值動態創建輸入類型文本。 如果數組值為5,則應創建五個輸入類型。

打字稿可以嗎? 還是我也應該在打字稿中使用以上代碼?

解決這種情況的最佳方法是什么?

創建一捆表單控件。 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">

使用*ngFor (這是一個Angular指令)來遍歷數組的元素。 如果在模型中您有public array = [1, 2, 3, 4] ,在模板中您有

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

這將打印以下DOM:

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

因此,對於您的問題,要創建輸入,只需將輸入放入循環中即可。

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

順便說一下,這是Angular模板中的基本操作。 我敦促您從官方站點閱讀Angular的官方介紹,以了解Angular可以做什么。

零件:

public inputControlsArr : Array<any> = [];

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

模板:

<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