2016-04-18 172 views
4
<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()上它後驗證失敗。我已經拿出下面的代碼來驗證每個輸入。角2 - 訪問/獲取的* ngFor和ngModel

for (var product of <any>this.products) { 
    if (product.service_type_id == 2 && !product.msisdn) { 
     alert('something'); 
     //Get the element and set focus here. 
    } 
} 

這是一個很好的方法嗎?在Angular 2中處理這個問題有更好的方法嗎?

+0

這是否解決問題了嗎? –

回答

7

的一種方法來獲得與*ngFor創建的元素的引用是@ViewChildren()

如果元件實際上是部件或指令,則該組件/指令類型可以作爲參數,否則可以添加模板變量和的名稱被傳遞模板變量(如字符串)可用於查詢元素。

在這種情況下,兩個模板變量和組件類型返回組件實例,但調用的焦點,我們需要因此ElementRef.nativeElement我創建了一個應用的輔助指令ion-input和用於查詢的元素,也叫focus()

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(); 
    } 
} 

參見Angular 2: Focus on newly added input element

Plunker example

+2

其實並不那麼簡單。我創建了一個[** Plunker示例**](https://plnkr.co/edit/JUMdao?p=preview)。 –

+0

很酷的解決方案,Günter!我認爲能夠使用表單控件做些什麼... –