为什么输入的值会立即显示?怎么解决?

问题描述 投票:0回答:1

为什么我在输入栏中输入的值会立即显示,而不是点击添加按钮后才出现?”

问题是 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>


angular typescript angular18
1个回答
-1
投票

您正在使用双向数据绑定,它会立即更新属性。

示例项目在 Stackblitz 上管理。 检查这里

© www.soinside.com 2019 - 2024. All rights reserved.