[英]How to sync variable value on template in Angular 7?
I have a form that user can register the accounts, when user type in the username, if there's already existed account the error message will show up. 我有一个用户可以注册帐户的表格,当用户键入用户名时,如果已经存在帐户,则会显示错误消息。 However as I check this by event, the check flag only render once and not binding again if user delete the text and reinput. 但是,当我按事件进行检查时,如果用户删除文本并重新输入,则检查标志仅呈现一次,并且不会再次绑定。
My form on my component HTML: 我在组件HTML上的表单:
<label for="Username">Username:</label>
<input type="text" (keyup)="ConfirmDataBeforeSubmission(regisUsername.value)" pattern="^[a-zA-Z0-9]+$" required name="Username" id="Username" class="modal_input" #regisUsername='ngModel' ngModel />
<!-- Errors -->
<div class="has-text-danger" *ngIf="(regisUsername.touched || regisUsername.dirty) && (regisUsername.errors)">
<div *ngIf="regisUsername.errors?.required">
Username can't be blank
</div>
<div *ngIf="regisUsername.errors?.pattern">
Username can't have special characters/space
</div>
</div>
<div *ngIf="duplicateAccount">
Username already exists
</div>
My component ts file that handle the error 我的组件ts文件处理错误
duplicateAccount = false;
UserListFromAPI: User[] = [];
ConfirmDataBeforeSubmission(username: string) {
this.myAPIService.GetListUser().subscribe((list) => {
this.UserListFromAPI = list;
});
this.UserListFromAPI.forEach(element => {
if (element.Username === username) {
this.duplicateAccount = !this.duplicateAccount;
}
});
}
Is there any solution ? 有什么解决办法吗? I'm new to Angular so any help/suggestion would be appreciated. 我是Angular的新手,所以任何帮助/建议都将不胜感激。
Why you are calling API every time when the user types anything in the textbox? 当用户在文本框中键入任何内容时,为什么每次都要调用API?
I would rewrite the code like this: 我将这样重写代码:
import { Component, OnInit } from '@angular/core';
/** @title Simple form field */
@Component({
selector: 'form-field-overview-example',
templateUrl: 'form-field-overview-example.html',
styleUrls: ['form-field-overview-example.css'],
})
export class FormFieldOverviewExample implements OnInit {
duplicateAccount = false;
UserListFromAPI: User[] = [];
ngOnInit() {
this.GetUserList();
}
ConfirmDataBeforeSubmission(username: string) {
this.UserListFromAPI.forEach(element => {
if (element.Username === username) {
this.duplicateAccount = !this.duplicateAccount;
}
});
}
GetUserList() {
this.myAPIService.GetListUser().subscribe((list) => {
this.UserListFromAPI = list;
});
}
}
Please check and let me know if its working or not! 请检查并让我知道它是否有效!
EDIT: 编辑:
I will rewrite the function ConfirmDataBeforeSubmission()
: 我将重写功能ConfirmDataBeforeSubmission()
:
ConfirmDataBeforeSubmission(username: string) {
this.duplicateAccount = this.UserListFromAPI.some(x => x.Username == username);
}
Here is working example without API call (ie with Sample data) 这是没有API调用的工作示例(即带有示例数据)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.