有没有办法专注于 Angular 4/Ionic3 上动态创建的表单? [英] Is there a way to focus on a dynamically created form on Angular 4/Ionic3?

查看:26
本文介绍了有没有办法专注于 Angular 4/Ionic3 上动态创建的表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态创建表单的页面,如下所示:

空格是输入,整行是一个按钮.有没有办法点击按钮,即整行,然后选择/关注对应的输入?请记住,输入的数量是由用户决定的,最多可以有页面上有 300 行这样的行.

I have a page with dynamically created forms like this:

The blank spaces are inputs and the entire row is a button. Is there a way to click on the button, i.e. the entire row, and select/focus on the correspondent input? Keep in mind that the number of inputs is determined by the user and there can be up to 300 rows like these on the page.

export class HomePage {

      public homeForm: FormGroup;
      
      constructor(
        public navCtrl: NavController,
        public userData: UserDataProvider,
        private formBuilder: FormBuilder,
        public renderer: Renderer,
        public elementRef: ElementRef
      ) {

        this.homeForm = new FormGroup({
          bicos: new FormArray([
            new FormControl(null)
          ])
      });

       addInputs() {
          (<FormArray>this.homeForm.controls['bicos'])
          .push(new FormControl(null));
    }
}

home.html:

<form [formGroup]="homeForm"> 
    <ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" >
        <button id={{i}} ion-button clear style="color: black" class='hidden-button' (click) = "doSomething()">
    <ion-col align-self-center col-2>{{i+1}}</ion-col>
         <ion-col text-center align-self-center col-5>
           <ion-input type="text"></ion-input>
         </ion-col>
             <ion-col align-self-center col-5>400</ion-col>
         </button>
    </ion-row>
</form>

我已经尝试过使用指令等但没有成功.

I have already tried using directives and such without success.

推荐答案

您可以使用 ViewChildren 根据索引引用输入.将模板引用 #inputs 添加到您的输入字段:

You can use ViewChildren to reference the inputs based on index. Add template ref #inputs to your input field:

<ion-input #inputs type="text"></ion-input>

在您的组件中导入 ViewChildrenQueryList 和...

In your component import ViewChildren and QueryList and...

@ViewChildren('inputs') inputs: QueryList<any>;

然后单击按钮,在您提供的代码中调用 doSomething,传递索引并根据索引将焦点设置在该字段上:

Then on your button click, where you call doSomething, in the code you presented, pass the index and set the focus on that field based on index:

<ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" >
  <button ion-button (click) = "doSomething(i)">
  <!-- ... -->

TS:

doSomething(index) {
  this.inputs.toArray()[index].setFocus();
}

这篇关于有没有办法专注于 Angular 4/Ionic3 上动态创建的表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆