2017-09-26 69 views
-1

非常简单,我有一个包含sting的组件Angular2在输入字段中单向数据绑定

我需要在输入fieid中显示此字符串。

我以为我需要这样但它不起作用。

// Component 

import {Component} from "@angular/core"; 

@Component({ 
    selector: 'my-component', 
    templateUrl: './my-compoent.template.html'; 
}) 

export class MyComponent{ 

    constructor(){ 

    } 

    myVar: string = "Hello World" 

} 


// HTML 

<input type="text" ([ngModel])="myVar" > 
+0

使用'[(ngModel)] = “myVar的”'(或'[ngModel] = “myVar的”'如果只是单向绑定) – amal

+0

真您ngModel语法错误 –

+0

'[ngModel] =” myVar“'不起作用 – ttmt

回答

1

解决方案是:

([ngModel])= “myVar的”=> [(ngModel)] = “myVar的”

添加名称字段中输入类型名称= “myVar的”

尝试像这样:

import { Component } from "@angular/core"; 

@Component({ 
    selector: 'my-component', 
    templateUrl: './my-compoent.template.html'; 
}) 
export class MyComponent { 
    myVar: string = "Hello World" 
    constructor() { } 
} 

在HTML中,你需要输入型加名

<input type="text" name="myVar" [(ngModel)]="myVar" > 
+0

谢谢,这是我错过的名字。 – ttmt

+1

名称与此无关,它是固定它的双向数据绑定的parans顺序。 –

+0

这是一个错别字,对不起,这是为我修复它的名字。 – ttmt

0

([ngModel])语法是错误的,它应该是[(ngModel)]。注意parans的顺序。

助记符是香蕉盒[看起来像一个盒子,(看起来像一根香蕉。


而且你似乎有路径到您的模板文件一个错字,它说的./my-compoent代替./my-component这是什么文件可能命名。