【问题标题】:Angular2 one way databinding in input fieldAngular2输入字段中的单向数据绑定
【发布时间】:2018-03-07 21:26:19
【问题描述】:

很简单,我有一个包含字符串的组件

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

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

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

@Component({
    selector: 'my-component',
    template: `
        <input type="text" ([ngModel])="myVar" >
    `
})

export class MyComponent{

  constructor(){
  } 

  myVar: string = "Hello World"

}

【问题讨论】:

  • 使用[(ngModel)]="myVar"(或[ngModel]="myVar",如果它只是单向绑定)
  • 你的 ngModel 语法是错误的
  • [ngModel]="myVar" 不起作用
  • @ttmt 您不需要 name 属性,除非您将此输入用作模板驱动的 formControl(原始 OP 中未提及)。为了实现input 字段和组件属性之间的绑定,只需正确的“banana-in-a-box”语法就足够了。请参阅this 以了解有关实现 2 路绑定的更多信息。另外,就像我提到的,[ngModel] 只是单向绑定——这意味着它会在初始加载时将值从组件一次填充到视图。

标签: angular typescript input data-binding


【解决方案1】:

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

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


另外,您的模板文件的路径似乎有错字,它显示的是./my-compoent,而不是文件可能命名的./my-component

【讨论】:

    【解决方案2】:

    解决办法是:

    ([ngModel])="myVar" => [(ngModel)]="myVar"

    在输入类型name="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" >
    

    【讨论】:

    • 谢谢,这是我错过的名字。
    • 名称应该与此无关,修复它的是双向数据绑定的参数顺序。
    • 这是一个错字,抱歉,这是为我改正的名称。
    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2015-08-08
    • 1970-01-01
    • 2017-03-18
    • 2017-01-13
    • 2022-01-23
    相关资源
    最近更新 更多