0

不能在AfterViewInit挂钩上选择动态值。该值可能会在 angulars 生命周期的后期选择;它实际上与AfterViewChecked钩子一起工作,但这将迫使我设置一个标志,因此它只在第一次运行。这似乎是一个过于复杂的解决方案。我也得到了ExpressionChangedAfterItHasBeenCheckedError生产,这是有道理的。

input在没有这些生命周期错误的情况下,在加载组件时选择动态值的简单/正确方法是什么?

查看此stackblitz以获取演示。

这是我使用AfterViewChecked钩子的一些代码。

app.component.ts

import { Component, ViewChild, AfterViewChecked } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewChecked {
  @ViewChild('myInput') public myInput;
  public value = 1;
  ngAfterViewChecked() {
    this.myInput.nativeElement.focus();
    this.myInput.nativeElement.select();
  }
}

app.component.html

<mat-form-field class='amount' appearance="standard">
    <mat-label>Convert</mat-label>
    <input #myInput matInput [(ngModel)]='value' />
</mat-form-field>

编辑:我在mat-form-field代码中添加了它可能是相关的。

4

1 回答 1

0

创建指令,以便我们可以通过注入 NgControl 来访问 ngModel 实例。然后在 valueChanges 里面我们可以设置焦点和选择。

尝试这个:

import { Directive, AfterViewInit,OnInit, ElementRef,OnDestroy } from '@angular/core';
import { NgControl } from '@angular/forms';
import {take,} from 'rxjs/operators';
import {Subscription} from 'rxjs';

@Directive({
  selector: '[appFocus]'
})
export class FocusDirective implements OnInit, OnDestroy {
  subscription = new Subscription();
  constructor(private elem: ElementRef, private ngControl:NgControl) { }

  ngOnInit(){
    this.subscription.add(this.ngControl.control!.valueChanges.pipe(take(1)).subscribe(v=>{
      console.log(v);
      this.elem.nativeElement.focus();  
      this.elem.nativeElement.select(); 
    }));  
  } 

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
} 

例子

于 2020-08-03T16:12:03.290 回答