【问题标题】:Angular Form Template One-Way Data BindingAngular 表单模板单向数据绑定
【发布时间】:2017-11-07 03:46:08
【问题描述】:

我正在尝试单向绑定到我的 HTML 表单中的默认值。

我的组件有一个正在从本地存储初始化的连接字符串:

export class AuthAdminComponent implements OnInit {

  public authenticated = false;
  public connection: String
  public username: string;
  public password: string;
  public token: string;

  constructor(private authService: AuthService, private router: Router) {

   }

  ngOnInit() {
    if(localStorage.getItem('adminUser')) {
      let data = JSON.parse(localStorage.getItem('adminUser'));
      this.connection = data.connection;
      this.username = data.username;
      this.password = data.password;    }
  }
}

然后在我的表单中,我尝试单向绑定到这些属性,例如连接。但是,它返回 [object Object]。我似乎无法弄清楚如何获得实际价值:

<label for="connection">Connection</label>
            <input 
            class="input__username" 
            type="text" 
            name="connection"
            required
            [ngModel]="connection"
            #connection="ngModel" />
            <span *ngIf="!connection.valid && connection.touched">Please enter a valid connection string.</span>

我确定这很简单,我误解了。如果有人可以向我解释我缺少什么,我将不胜感激。谢谢!

【问题讨论】:

  • 因为connection 是一个对象?

标签: forms angular data-binding


【解决方案1】:

这是您的问题:
您正在尝试将 ngModel 绑定到您的类中定义的变量连接。
另一方面,您将#connection 定义为输入元素上的引用变量。
因此,ngModel 将绑定到此变量,而不是您的类中定义的变量。
一种可能的解决方案是将 #connection 重命名为 #connect(或者您可以在您的类中重命名 connection 并将 ngModel 绑定到模板中重命名的变量)。
这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多