我大部分时间都有工作的Angular反应形式。但是有时候,我随机得到一个错误

ERROR Error: Cannot find control with name: 'username'
    at _throwError (forms.js:2337)
    at setUpControl (forms.js:2245)
    at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5471)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:6072)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5993)
    at checkAndUpdateDirectiveInline (core.js:21093)
    at checkAndUpdateNodeInline (core.js:29495)
    at checkAndUpdateNode (core.js:29457)
    at debugCheckAndUpdateNode (core.js:30091)
    at debugCheckDirectivesFn (core.js:30051)


该组件是一个简单的登录页面,HTML是

<div id="loginSection" class="middle-dashboard-box">
  <div class="login-title content-inner-title" i18n="logintitle|@@loginheader">Login</div>
  <form class="login-form" [formGroup]="loginFormGroup" (ngSubmit)="login($event)">
    <mymat-form-error></mymat-form-error>
    <div>
      <mat-form-field class="login-input input-control-width">
        <input matInput formControlName="username" i18n-placeholder="Username|@@username" placeholder="Username">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field class="login-input input-control-width">
        <input matInput formControlName="password" type="password" i18n-placeholder="Password|@@password" placeholder="Password">
      </mat-form-field>
    </div>
    <div class="forgot-pass">
      <a href="#public/forgotpassword" i18n="forgot password|@@forgotPasswordLink">Forgot password?</a>
    </div>
    <button mat-raised-button color="primary" type="submit" class="main-btn login-btn"
      i18n="Login|Login button action@@login">Login</button>
  </form>
</div>


TS是

@Component( {
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
} )
export class LoginComponent implements OnInit {

    loginFormGroup: FormGroup;

    constructor( private router: Router,
        private formBuilder: FormBuilder,
        private loginService: LoginService ) { }

    ngOnInit() {
        this.loginFormGroup = this.formBuilder.group( {
            username: ['', Validators.required],
            password: ['', Validators.required]
        } );
        this.loginFormGroup.controls['username'].setValue( this.loginService.latestUsername );
    }

    login( event ) {
        // do login stuff, not relevant here
    }
}


this.loginService.latestUsername指向LoginService中的获取器:

get latestUsername(): string {
    return localStorage.getItem( LoginService.LATESTUSERNAME_KEY ) || ''
}


stacktrace中的FormControlName.ngOnChanges使我认为ng在控件正确初始化之前正在运行更改检测,但是由于周围没有订阅或类似内容,因此我看不到是什么触发了它。
我正在Selenium测试期间观察到错误(某些测试可靠地进行,而其他测试则间歇地进行),但是在手动单击时出现了一次或两次。该效果仅在升​​级到Angular 8.2.14(从7开始)之后发生

最佳答案

查看FormControlNamesource code并考虑when ngOnChanges() can run,我认为ngOnChanges()ngOnInit()完成构建表单之前正在运行。

为了诊断这一点,我将ngOnChanges()ngOnInit()都用console.log()乱码,以跟踪发生的情况。

要解决此问题(如果是原因所在),它应该与使用*ngIf保护表单一样简单,以确保指令不会过早触发更改检测。理想情况下,您还可以使用OnPush更改检测策略。

10-06 11:49