我是角度2的新手,我的代码有问题。 当maxlength到达时,我正在尝试将input1焦点更改为input2。 现在,我计算按下的键的数量并与maxlength进行比较。 我不明白如何使用.focus属性... 我已经尝试了指令,但我再次失败,我没有其他想法来解决这个问题......这让我发疯! 有人可以帮助我吗?
@Component({
moduleId: module.id,
selector: 'sd-about',
template: `
<span (ngSubmit)="onMovieSubmit()" *ngFor="let MovieField of MovieTab">
<input
type="text"
maxlength="6"
size="3"
#movieName
(keyup)= presskeyNumber(movieName.value.length,MovieField.length,MovieField.id)><br/>
</span>
`
})
export class AboutComponent {
@Output() RestrictionNumber:number;
public presskeyNumber(movieName: any, restriction: number, MovieField: number) {
this.RestrictionNumber = restriction;
if (movieName === this.RestrictionNumber) { // If my movie field length = my maxlength
console.log('fieldFocus : ', MovieField + 1); // The next input Id
// Change focus here
}
}
public MovieTab = [
{ id: 1, movieName: "Movie1", length: 6 },
{ id: 2, movieName: "Movie2", length: 6 },
{ id: 3, movieName: "Movie3", length: 6 }
];
}
答案 0 :(得分:0)
@ViewChild('movieName') movieName
public presskeyNumber(movieName: any, restriction: number, MovieField: number) {
this.RestrictionNumber = restriction;
if (movieName === this.RestrictionNumber) { // If my movie field length = my maxlength
console.log('fieldFocus : ', MovieField + 1); // The next input Id
// Change focus here
this.movieName.nativeElement.focus()
}
}
如果你想在循环中使用它,也许它更容易将局部变量作为参数传递给你的方法:
<span (ngSubmit)="onMovieSubmit()" *ngFor="let MovieField of MovieTab">
<input
type="text"
maxlength="6"
size="3"
#movieName
(keyup)= presskeyNumber(movieName, movieName.value.length,MovieField.length,MovieField.id)><br/>
</span>
然后:
public presskeyNumber(movieNameElement, movieName: any, restriction: number, MovieField: number) {
this.RestrictionNumber = restriction;
if (movieName === this.RestrictionNumber) { // If my movie field length = my maxlength
console.log('fieldFocus : ', MovieField + 1); // The next input Id
// Change focus here
movieNameElement.focus()
}
}
这样,您就不需要使用ViewChild
,因为您已将输入元素传递给您的函数。