【发布时间】:2019-12-06 15:43:15
【问题描述】:
问题
我想知道当一个新元素被添加到它正在动态跟踪的数组中时,Angular 已经完成渲染 *ngFor 指令(编辑:),并且在 ngAfterViewInit 之后。
示例
我的问题的一个例子:我有一个包含 2 个东西的数组。使用 ngFor 将它们生成为内容可编辑的 p 标签。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p
*ngFor="let el of myArray"
contenteditable="true"
(keydown.enter)="addNewP()"
>{{el}}</p>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
myArray = ["first", "second"];
addNewP(){
this.myArray.splice(1, 0, "in the middle");
}
}
如何在用户按下回车后获得 angular 已完成渲染的异步通知,以便我可以将焦点放在“中间”元素上?
我目前的解决方案
目前我正在使用来自https://www.codementor.io/yomateo/auto-focus-with-angular-7-the-directive-osfcl7rrv 的自定义指令:
import { Directive, ElementRef, AfterContentInit } from '@angular/core';
@Directive({
selector: '[appFocusNew]'
})
export class FocusNewDirective implements AfterContentInit{
constructor(private el: ElementRef//tiny side note: angular warns extensively against this, should i avoid it?
) { }
public ngAfterContentInit() {
setTimeout(() => {
this.el.nativeElement.focus();
},0)
}
}
【问题讨论】:
标签: angular