ng2 [disabled] =“!myInput.value”无法正常工作

艾塔克世界

我正在构建一个标准的angular2应用程序(更具体的是todo应用程序)。我还添加了@ Ngrx / store

第一次加载页面时,该按钮被禁用,但是当我在输入框中输入一些值时,该按钮需要被启用,但它保持禁用状态。

app/app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
  <h1>Hello {{name}}</h1>
  <div>
    <add-todo></add-todo>
  </div>`,
})
export class AppComponent  { name = 'Angular'; }

app/components/add-todo/add-todo.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'add-todo',
  template: `
    Create new todo
    <input #myInput />
    <button (click)="addTodo()" [disabled]="!myInput.value">Add</button>`
})
export class AddTodoComponent {
  @ViewChild('myInput') input: ElementRef;

  constructor() {}

  addTodo(): void {
    alert(this.input.nativeElement.value);
  }
}

埃文斯M.

从文档https://angular.io/docs/ts/latest/guide/forms.html使用ngModel跟踪表单控件的更改状态和有效性...

更新您的代码以使用ngModel,它应该可以按预期工作

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'add-todo',
  template: `
    Create new todo
    <input #myInput [(ngModel)]="inputFieldValue" />
    <button (click)="addTodo()" [disabled]="!myInput.value">Add</button>`
})
export class AddTodoComponent {

  @ViewChild('myInput') input: ElementRef;
  public inputFieldValue:string = '';

  constructor() {}

  addTodo(): void {
    alert(this.input.nativeElement.value);
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章