【问题标题】:Property binding of value attributevalue 属性的属性绑定
【发布时间】:2018-10-19 08:04:52
【问题描述】:

我是 Angular 5 的新手,目前正在学习基础知识。 我了解了模板引用变量。但我有一个问题。 我没有使用模板引用变量,而是尝试使用带有类变量的输入元素的“值”属性进行属性绑定,并在单击按钮时尝试登录类变量,但它不起作用。请让我知道我哪里出错了。

这是我的代码

@Component({
  selector: 'app-test',
  template: `

  <input type="text" value="{{greet}}"/>
  <button (click)="logMe()">Click </button>
  `,
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

public greet="";

  constructor() { }

  ngOnInit() {
  }
logMe()
{
console.log(this.greet);}
}

【问题讨论】:

  • 你在控制台得到了什么?

标签: angular


【解决方案1】:

这不会记录任何内容,因为绑定只是单向的。如果要查看greet 变量中的输入值,请改用ngModel

在您的app.module.ts 中导入FormsModule 并按以下方式更改代码:

@Component({
  selector: 'app-test',
  template: `

  <input type="text" [(ngModel)]="greet"/>
  <button (click)="logMe()">Click </button>
  `,
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

public greet="";

  constructor() { }

  ngOnInit() {
  }
logMe()
{
console.log(this.greet);}
}

【讨论】:

    【解决方案2】:

    Angular 有一种完全不同的方式来绑定表单输入。

    我认为您正在尝试实现两个数据绑定。

    所以这样做的角度方式。

    <input type="text"  [(ngModel)]="greet"/>
    

    由于我们是新手,您可以使用 stackblitz 发布工作 Angular 代码

    https://stackblitz.com/edit/angular-b9qubm?file=src%2Fapp%2Fapp.component.html

    【讨论】:

      猜你喜欢
      • 2010-11-26
      • 2011-01-15
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多