为什么我在输入栏中输入的值会立即显示,而不是点击添加按钮后才出现?”
问题是 inputValue 使用 [(ngModel)]="inputValue" 通过双向绑定立即绑定到 app-new-todo 组件。因此,一旦用户在输入字段中键入内容,就会显示输入的值。我希望它仅在单击“添加”按钮后出现。
如何调整代码,不让立即显示,保证任务只在按钮点击后才显示?
这是代码:
export interface TodoData {
id: number;
todo: string;
done: boolean;
}
export class TodoComponent {
@Output() todo = new EventEmitter<TodoData>();
inputValue = '';
done = false;
addTask() {
this.todo.emit({
id: Math.floor(Math.random() * 1000),
todo: this.inputValue,
done: this.done,
});
}
}
HTML:
<section>
<form (ngSubmit)="addTask()">
<div>
<input
name="todo"
type="text"
placeholder="Enter new task"
[(ngModel)]="inputValue"
/>
<button>ADD</button>
</div>
</form>
<app-new-todo [task]="inputValue" />
</section>
export class AppComponent {
onAddTask(data: { id: number; todo: string; done: boolean }) {
console.log(data.todo);
}
}
HTML:
<app-header />
<app-todo (todo)="onAddTask($event)" />
export class NewTodoComponent {
@Input({ required: true }) task!: string;
}
HTML:
<div>
<h1>{{ task }}</h1>
</div>