大佬教程收集整理的这篇文章主要介绍了typescript – Angular 2 – 在* ngFor和ngModel中访问/获取输入元素,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<ion-card *ngFor='#product of products | mapToIterable:"key":true'> <ion-list> <ion-item> <ion-label stacked>Account No. / Phone No.</ion-label> <ion-input type="text" [(ngModel)]="product.msisdn"></ion-input> </ion-item> <ion-item> <ion-label stacked>amount</ion-label> <ion-input type="text" (keypress)="isnumberKey($event)" [(ngModel)]="product.amount"></ion-input> </ion-item> </ion-list> </ion-card>
参考上面的html,我如何得到离子输入的参考,以便在验证失败后我可以在它上面设置setFocus().我已经提出了下面的代码来验证每个输入.
for (var product of <any>this.products) { if (product.service_type_id == 2 && !product.msisdn) { alert('something'); //Get the element and set focus here. } }
如果元素实际上是组件或指令,则组件/指令类型可以作为参数传递,否则可以添加模板变量,并且模板变量的名称(作为字符串)可用于查询元素.
在这种情况下,模板变量和组件类型都返回组件实例,但是为了@L_772_11@焦点,我们需要ElementRef.nativeElement,因此我创建了一个应用于ion-input的辅助指令,用于查询元素以及@L_772_11@焦点():
import {Component,Directive,Renderer,HostListener,ViewChildren,ElementRef} from 'angular2/core' /// Helper directive @Directive({ SELEctor: 'ion-input' }) class Focusable { constructor(public renderer: Renderer,public elementRef: ElementRef) {} focus() { console.debug(this.elementRef.nativeElement); this.renderer.invokeElementMethod( this.elementRef.nativeElement,'focus',[]); } } /// Test component instead of the original ion-input @Component({ SELEctor: 'ion-input',host: {'tabindex': '1'},template: ` <div>input (focused: {{focuseD}})</div> `,}) export class IonInput { focused:Boolean = false; @HostListener('focus') focus() { this.focused = true; } @HostListener('blur') blur() { this.focused = false; } } /// Queries the elements and calls focus @Component({ SELEctor: 'my-app',directives: [IonInput,Focusable],template: ` <h1>Hello</h1> <div *ngFor="let product of products"> <ion-input #input type="text"></ion-input> </div> <button *ngFor="let product of products; let index=index" (click)="setFocus(indeX)">set focus</button> `,}) export class AppComponent { constructor(private renderer:renderer) { console.debug(this.renderer) } products = ['a','b','c'] @ViewChildren(FocusablE) inputs; ngAfterViewInit() { // `inputs` is Now initialized // iterate the elements to find the desired one } setFocus(indeX) { // `inputs` is Now initialized // iterate the elements to find the desired one //var input = ... //console.debug(this.inputs.toArray()[1]); this.inputs.toArray()[index].focus(); } }
以上是大佬教程为你收集整理的typescript – Angular 2 – 在* ngFor和ngModel中访问/获取输入元素全部内容,希望文章能够帮你解决typescript – Angular 2 – 在* ngFor和ngModel中访问/获取输入元素所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。