【问题标题】:How to sync variable value on template in Angular 7?如何在 Angular 7 中同步模板上的变量值?
【发布时间】:2019-08-04 05:10:32
【问题描述】:

我有一个用户可以注册帐户的表单,当用户输入用户名时,如果已经存在帐户,则会显示错误消息。 但是,当我按事件检查时,如果用户删除文本并重新输入,检查标志只会呈现一次并且不会再次绑定。

我的组件 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>

我处理错误的组件 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;
      }
    });

  }

有什么解决办法吗?我是 Angular 的新手,所以任何帮助/建议都将不胜感激。

【问题讨论】:

    标签: angular typescript data-binding


    【解决方案1】:

    为什么每次用户在文本框中输入任何内容时都调用 API?

    我会这样重写代码:

    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;
        });
      }
    }
    

    请检查并告诉我它是否有效!

    编辑:

    我将重写函数ConfirmDataBeforeSubmission()

    ConfirmDataBeforeSubmission(username: string) {
       this.duplicateAccount = this.UserListFromAPI.some(x => x.Username == username);
    }
    

    这是没有 API 调用的工作示例(即带有示例数据)

    StackBlitz

    【讨论】:

    • 天啊,你重写的函数就像一个魅力! :D 非常感谢
    猜你喜欢
    • 2018-08-04
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多