我尝试以编程方式提交表单并检查formgroupdirective的提交状态,但始终设置为false。如何触发它设置为true?
TS:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid);
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
isShowErrors: boolean = false;
sampleForm: FormGroup;
@ViewChild('testForm') testForm: NgForm;
constructor(private fb: FormBuilder, private el: ElementRef){}
ngOnInit(){
this.sampleForm = this.fb.group({
name: ['', Validators.required]
});
}
matcher = new MyErrorStateMatcher();
submit(){
this.isShowErrors = true;
console.log(this.testForm);
if(this.sampleForm.valid){
//navigate
}
}
buttonClick(){
this.testForm.ngSubmit.emit();
}
}
HTML:
<form [formGroup]="sampleForm" (ngSubmit)="submit()" #testForm="ngForm">
<mat-form-field>
<input matInput type="text" formControlName="name" [errorStateMatcher]="matcher">
<mat-error *ngIf="!sampleForm.valid && isShowErrors">This field is invalid</mat-error>
</mat-form-field>
</form>
<button type="button" (click)="buttonClick()">Submit</button>
答案 0 :(得分:0)
在为表单提供id
且该名称与该按钮的form
属性相同时,删除该按钮上的(click)
事件并更改type
即可提交,我能够将提交的值触发为true。
HTML现在看起来像这样:
<form id="sampleForm" [formGroup]="sampleForm" (ngSubmit)="submit()" #testForm="ngForm">
<mat-form-field>
<input matInput type="text" formControlName="name" [errorStateMatcher]="matcher">
<mat-error *ngIf="!sampleForm.valid && isShowErrors">This field is invalid</mat-error>
</mat-form-field>
</form>
<button type="submit" form="sampleForm">Submit</button>
但是,我仍然想知道是否可以使用click事件和类型作为按钮来完成。