gpt4 book ai didi

angular - 尝试在按钮单击时重置表单

转载 作者:太空狗 更新时间:2023-10-29 18:27:52 30 4
gpt4 key购买 nike

我正在使用基本凭据创建一个基本示例用户注册应用程序。我试图在单击取消按钮时重置表单。但是我无法这样做。我已经编写了重置函数,但不知何故它没有被调用。我不知道出了什么问题。请帮忙。提前致谢

我的代码:

 ngOnInit()
{

this.addForm = this.formBuilder.group({
id: [],
userName: ['', Validators.required],
password:new FormControl( '',[ Validators.required]),
passwordAgain: new FormControl('',[ Validators.required]),
userRole:['',Validators.required],

},{ validator: RepeatPasswordValidator });
}
onSubmit() {
if (this.addForm.valid)
{
this.userService.createUser(this.addForm.value)
.subscribe( data => {

//this.router.navigate(['adduser']);
});
this.snackBar.open("message", "action", {
duration: 2000,
});
alert("User created");

}

window.location.reload();
}
changeClient(value) {

}
resetForm()
{
this.addForm.reset();
}

这是我的模板:

<div  style="height: 100vh" fxLayout="column" fxLayoutAlign="center center" >
<mat-toolbar>
<span>Registration</span>
</mat-toolbar>
<mat-card>
<mat-card-content>

<form [formGroup]="addForm" class="login-form" (ngSubmit)="onSubmit()">
<div class="form-group">
<mat-form-field class="example-full-width">

<input matInput type="text" formControlName="userName" placeholder="userName" name="userName" class="form-control" id="userName">
</mat-form-field>
</div>

<div class="form-group">
<mat-form-field class="example-full-width">

<input matInput type="password" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
<mat-error *ngIf="addForm.controls.password.hasError('required')" >Passwords can't be empty</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-form-field>
<input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
<mat-error *ngIf="addForm.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
</mat-form-field>
</div>
<mat-form-field>
<mat-select placeholder="Roles" formControlName="userRole" id="userRole" (selectionChange)="changeClient($event.value)" [(value)]="selected">
<mat-option value="Admin">Admin</mat-option>


</mat-select>
</mat-form-field>

<div class="container" style="margin: 12px" fxLayout="row" fxLayoutAlign="center center">


<button mat-raised-button color="primary">Create</button>
<button mat-raised-button (click)= 'resetForm()' color="primary">Cancel</button>


</div>
</form>


</mat-card-content>
</mat-card>
</div>

最佳答案

它应该在 resetForm() 方法中带有括号 (),如下所示:

this.addForm.reset();

更新的答案:

此外,尝试为取消按钮提供 type=reset,如下所示

<button mat-raised-button type=reset (click)= 'resetForm()' color="primary">Cancel</button>

关于angular - 尝试在按钮单击时重置表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55631032/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com