gpt4 book ai didi

typescript - Angular 2 - 访问/获取 *ngFor 和 ngModel 中的输入元素

转载 作者:太空狗 更新时间:2023-10-29 17:47:04 26 4
gpt4 key购买 nike

<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,如何获取ion-input的引用,以便我可以在验证失败后对其进行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.
}
}

这是一个好方法吗?在 Angular 2 中有更好的方法来处理这个问题吗?

最佳答案

获取使用 *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

关于typescript - Angular 2 - 访问/获取 *ngFor 和 ngModel 中的输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36695468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com