【问题标题】:How to get input value and pass it to angular component?如何获取输入值并将其传递给角度组件?
【发布时间】:2018-12-14 08:59:10
【问题描述】:

我是 Angular 新手,正在尝试创建一个简单的待办事项应用程序。

我使用 [(ngModel)] 将输入值传递给组件,但似乎我的做法不正确。

这是我的代码

HTML:

<div class="todo-app">
  <h1>Todo List</h1>
  <div>
    <input type="text" class="input" placeholder="Enter your task" autofocus="" [(ngModel)]="value">
    <button class="btn" (click)="addTodo()">Add</button>
  </div>
</div>

ts:

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


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl']
})

export class AppComponent {
  todos = [];
  id:number = 0;

  addTodo() {
    this.todos = [...this.todos, {title: this.value, id: this.id++, completed: false}];
    return this.todos;
  }

  removeTodo(id:number) {
   return this.todos.filter(todo => todo.id !== id)
  }

  toggleCompletionState(id:number) {
    this.todos.map(todo => todo.id === id ? {...todo, completed: !todo.completed} : todo)
  }

  getAllTodos() {
    return this.todos;
  }
}

这里出了什么问题以及为什么 ngModel 不起作用??

【问题讨论】:

  • 您忘记声明您的value 字段。不过,这应该可以工作(但是,当您拥有多个值时,将单个值存储为属性有点奇怪)。无论如何,请详细说明您的问题是什么。
  • 我很困惑,我什至不知道如何获取输入值并将其传递给组件以使用它,你能告诉我一个演示如何实现吗??

标签: angular


【解决方案1】:

在你的模板上,因为你已经在你的 ngModel 上分配了 value,所以也在你的 Component 上声明它以便能够在那里访问它的实例。

HTML

<input type="text" 
       class="input" 
       placeholder="Enter your task"
       [(ngModel)]="value">        // this 'value' must be instantiated on your component

组件

@Component({...}) {

   value: string;                  // Add this as you had used and assign it to your ngModel

   addTodo() {
      console.log(this.value);     // this will now have a value depends on your input from ngModel
   }

}

【讨论】:

    【解决方案2】:

    因为

     [(ngModel)]="someFieldInComponent"
    

    并且您的组件中没有someFieldInComponent(在您的情况下为value 字段)

    【讨论】:

    • 我现在添加了该字段,但没有任何效果!!,页面上甚至没有显示输入和按钮不知道为什么?
    • 准备堆栈闪电战
    • @Antoniossss 即使从打字稿的编译器的角度来看不声明该字段是无效的,它仍然可以转换为有效的 JS(因为您不必在 JS 中声明它)。所以问题必须在其他地方。
    • 我听不懂,当我在输入中使用[(ngModel)]="value" 时出现问题,它消失了,不知道为什么?
    • @Jeto 我只看了 这里有什么问题以及为什么 ngModel 不起作用,没有看到任何字段。
    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 2017-05-29
    • 2023-03-22
    • 2019-06-29
    • 2014-01-03
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多