我想在更改模型对象后设置光标位置,但它实际上尝试在更新文本框的值之前设置光标位置。
HTML:
<input type="text" name="test" id="test" [(ngModel)]="myString">
<button type="button" (click)="updateText('testStr')">
Run Code Online (Sandbox Code Playgroud)
TS:
myTextBox: HTMLInputElement;
ngOnInit() {
this.myTextBox = document.getElementById('test');
}
updateText(str:String){
this.myString+=str;
this.myTextBox.focus();
this.myTextBox.setSelectionRange(2,2);
}
Run Code Online (Sandbox Code Playgroud)
这样,因为它尝试在实际更新文本之前设置光标位置,所以它只能focus(). 但是,如果我没有将任何内容绑定到文本框并通过执行this.myTextBox.setAttribute('value',str);然后focus()调用它来更新其文本,setSelectionRange那么它就可以工作。我应该怎么办?
我刚刚在 上创建了一个空Angular项目IntelliJ,我正在尝试将一个文本框绑定到一个对象的成员。我的对象保留undefined或我在里面分配给它的任何东西OnInit。我包括FormsModule在app.module.ts,我无法让它工作。这是我的app.component.html文件:
<form #form="ngForm">
<input type="text" name="name" id="name" [ngModel]="person.name">
<button (click)="save()">save</button>
</form>
Run Code Online (Sandbox Code Playgroud)
这是app.component.ts:
import {Component, OnInit} from '@angular/core';
import {IPerson, Person} from './model/person.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'my-app';
names?: string;
person?: IPerson;
save() {
console.log('::::::' + this.person.name);
}
ngOnInit(): void {
this.person = new Person();
}
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts:
import { BrowserModule …Run Code Online (Sandbox Code Playgroud) 我意识到当我尝试使用forEach或map函数更改布尔数组的值时,这些值不会改变。我必须构造一个 for 循环并按索引更改元素。我想知道为什么会这样?