我正在构建一个标准的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);
}
}
答案 0 :(得分:1)
从文档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);
}
}
答案 1 :(得分:0)
如果你这样做会怎么样:
import {Component} from '@angular/core';
@Component({
selector: 'add-todo',
template: `
Create new todo
<input #todoTitleInput [(ngModel)]="todoTitle"/>
<button (click)="addTodo(todoTitleInput.value)" [disabled]="!todoTitle">Add</button>
`,
})
export class AddTodoComponent {
addTodo(title: string): void {
alert(title);
}
}