2017-06-06 55 views
1

我试图单向绑定到我的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> 

我敢肯定,这是简单的,我误解了。如果有人能向我解释我错过了什么,我将不胜感激。谢谢!

+1

因为'connection'是一个对象? – n00dl3

回答

1

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

+0

非常感谢! – codex