我正在构建一个使用角度形式的角度应用程序。它在角度5和角度6上都可以很好地工作。但是当我通过ng build -prod部署它时,会出现错误
这是我的logincomponent代码
<form class="md-float-material form-material" [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="text-center">
<img src="../../assets/images/logo.png" alt="logo.png">
</div>
<div class="auth-box card">
<div class="card-block">
<div class="row m-b-20">
<div class="col-md-12">
<h3 class="text-center">User Login</h3>
</div>
</div>
<div class="form-group form-primary">
<label for="username">Username</label>
<input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
<div *ngIf="f.username.errors.required">Username is required</div>
</div>
</div>
<div class="form-group form-primary">
<label for="password">Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
</div>
</div>
<div class="form-group form-primary">
<button class="btn btn-primary btn-md btn-block waves-effect waves-light text-center m-b-20">Login</button>
</div>
<div class="row">
<div class="col-md-2">
<img src="../../assets/images/Logo-small-bottom.png" alt="small-logo.png">
</div>
</div>
</div>
</div>
</form>
这是TS代码
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertService, UserService } from '../_services';
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent implements OnInit {
loginForm: FormGroup;
returnUrl: string;
selectedValue: 'observer';
constructor(
public formBuilder: FormBuilder,
public route: ActivatedRoute,
public router: Router,
public userService: UserService,
public alertService: AlertService) { }
public ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required],
});
this.userService.logout();
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
get f() { return this.loginForm.controls; }
public onSubmit() {
if (this.loginForm.invalid) {
return;
}
this.userService.login(this.loginForm.value)
.subscribe(
response => {
this.alertService.success('User Authenticated', true);
},
error => this.alertService.error(error, false)
);
}
}
答案 0 :(得分:1)
此错误是AoT(提前)编译的结果。
在运行“ ng serve”时未显示这些错误的原因是因为 ng serve 执行了JiT(Just in Time)编译。
在AoT编译中,您必须声明每个方法/变量以及许多其他内容。
一旦您在ts上定义了丢失的变量(如在LoginComponent上提交的变量),这些错误就会消失。
答案 1 :(得分:0)
在这种特定情况下,我将在我们的类中创建FormControl的实例。例如loginForm = new FormControl();
这是对您的问题的很好的解释: https://www.concretepage.com/angular-2/angular-2-formcontrol-example