我正在使用浏览器内编辑器,我希望用户能够选择一个单词,并立即开始输入以替换该单词。我计划在未来改变样式的外观,但目前我在编辑机制方面遇到了麻烦。
每次在输入字段中输入单词时,都会取消选中该区域,我必须再次单击输入框。这是代码中的问题还是我用角度构建它的方式?
这是应用程序工作演示的链接。控制台日志应显示我按下按钮的次数,并且您在每次输入后都会注意到该框被取消选中。
https://i.gyazo.com/c38c0edd506f9ed131d1bbcfef0e6f9f.mp4
我了解到我需要添加它以在@Component选择器中启用全局键控件:
host: { '(window:keydown)': 'onKey($event)' },
这是html模板:
<div class="content" *ngFor="let sentence of sentences; let s_i = index;">
<span class="content" *ngFor="let word of sentence; let i = index;">
<span *ngIf="(currentIndex === i) && (currentSentence === s_i) && !(editing)"
class="selectedWord"
(click)="onClick(s_i, i)">{{word}} </span>
<input *ngIf="(currentIndex === i) && (currentSentence === s_i) && (editing)"
class="editingWord"
(click)="onClick(s_i, i)"
type="text"
[(ngModel)]="sentences[s_i][i]">
<span *ngIf="(currentIndex !== i) || (currentSentence !== s_i)"
(click)="onClick(s_i, i)">{{word}} </span>
</span>
<br>
</div>
<span class="content" *ngFor="let word of array; let i = index;">
</span>
这是模板附加到的类(和相关方法):
export class EditorComponent {
text: string;
sentences: string[][];
sentenceCount: number;
currentSentence: number;
currentIndex: number;
editing: boolean;
constructor() {
this.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
var array = this.text.split(" ");
console.log(array);
this.sentences = [];
this.sentenceCount = this.sentences.push(array);
this.currentIndex = 0;
this.currentSentence = 0;
this.editing = false;
}
onKey(event: KeyboardEvent) {
var keycode = event.keyCode;
console.log("You pressed", keycode);
switch (keycode) {
case 13: // ENTER
this.createSentence();
break;
case 27: // ESC
this.finishWord();
break;
case 72: // 'h'
this.moveLeft();
break;
case 74: // 'j'
this.moveDown();
break;
case 75: // 'k'
this.moveUp();
break;
case 76: // 'l'
this.moveRight();
break;
case 82: // 'r'
this.editWord();
break;
}
}
private editWord = function() {
this.editing = true;
}
private finishWord = function() {
this.editing = false;
}
private isEditing = function() {
return this.editing;
}
}