首页 > 解决方案 > value 属性的属性绑定

问题描述

我是 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

解决方案


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

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

@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);}
}

推荐阅读