Angular 如何聚焦具有ngif的文本区域
我有以下角度2组件,我需要id为bannernote的Angular 如何聚焦具有ngif的文本区域,angular,Angular,我有以下角度2组件,我需要id为bannernote的textarea一旦可见(IsedetEnabled)就对焦 使用@ViewChild()装饰器检索textearea元素。 在文本区域中放置一个标识符,如下所示: 不要忘记实现AfterViewInit接口 @ViewChild('myTextarea') textArea; ngAfterViewInit() { this.textArea.focus(); } 使用@ViewChild()装饰器
textarea
一旦可见(IsedetEnabled
)就对焦
使用@ViewChild()
装饰器检索textearea元素。
在文本区域中放置一个标识符,如下所示:
不要忘记实现AfterViewInit接口
@ViewChild('myTextarea') textArea;
ngAfterViewInit() {
this.textArea.focus();
}
使用@ViewChild()
装饰器检索textearea元素。
在文本区域中放置一个标识符,如下所示:
不要忘记实现AfterViewInit接口
@ViewChild('myTextarea') textArea;
ngAfterViewInit() {
this.textArea.focus();
}
您可以使用
@ViewChild
访问代码中的元素。由于元素最初可能不可用,请将关联属性定义为setter,并在其中设置焦点。根据注释中的建议,首先检查元素引用是否已定义;当元素从视图中删除时,它将变为未定义
// Set the focus on the textarea as soon as it is available
@ViewChild("bannernote") set bannerNoteRef(ref: ElementRef) {
if (!!ref) {
ref.nativeElement.focus() ;
}
}
请参阅以获取演示。您可以使用
@ViewChild
访问代码中的元素。由于元素最初可能不可用,请将关联属性定义为setter,并在其中设置焦点。根据注释中的建议,首先检查元素引用是否已定义;当元素从视图中删除时,它将变为未定义
// Set the focus on the textarea as soon as it is available
@ViewChild("bannernote") set bannerNoteRef(ref: ElementRef) {
if (!!ref) {
ref.nativeElement.focus() ;
}
}
请参阅演示。我刚刚尝试了此
错误类型错误:无法读取未定义的属性“焦点”
我刚刚尝试了此错误类型错误:无法读取未定义的属性“焦点”
向ref
添加nullcheck,否则如果经常切换它,可能会引发错误。示例:@Stefan-感谢您的评论!我做了更正。@MauricioGraciaGutierrez-你不喜欢!!参考
?它比ref!==未定义的
。我在角度上没有问题(正如您可能猜到的),请随意重新编辑;-)将nullcheck添加到ref
,否则如果您经常切换它,它可能会引发错误。示例:@Stefan-感谢您的评论!我做了更正。@MauricioGraciaGutierrez-你不喜欢!!参考
?它比ref!==未定义的
。我在角度上没有问题(正如您可能猜到的),请随意重新编辑;-)