【问题标题】:Angular2 : Add textbox entry to a span on click of buttonAngular2:单击按钮将文本框条目添加到跨度
【发布时间】:2018-12-11 15:59:06
【问题描述】:

我对 Angular2 完全陌生,需要您的帮助来完成以下练习。我需要将文本框中的条目添加到 HTML 的跨度中。我被要求仅在 .ts 文件中进行更改

我无法理解需要在 AddMore 中添加什么以确保在单击复选框旁边的按钮时添加来自文本框的条目。 请帮忙

Angular.component.html:

<h1>Fresco PLAY Activity Tracker</h1>
<div>
    <div *ngFor="let todo of todos; let i=index" class="todoItem">
        <input type="checkbox" [(ngModel)]="todo.done" />
        <span [ngClass]="{'checked': todo.done}">{{i+1}}. {{ todo.desc }}</span>
    </div>
    <span *ngIf="todos.length == 0">No Activities to track! Start by adding one</span><br/>
    <input id="newTodo" type="text" [(ngModel)]="newToDo">
    <span *ngIf="error" style="color:red;">Please enter an activity!</span>
    <br/>
    <button id="addActivity" (click)="addMore()">Add an Activity!</button>
    <button id="clearAll" (click)="clearAll()">Clear All</button>
</div>

App.component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //Define your variables done,todos,newToDo,newToDoObj,error
 public done: boolean;
  public todos : any;
  public newToDo : string;
  public newToDoObj : any;
  public error : boolean;
  //Define your constructor here with todos as [] ,newToDo as '' and error as false
constructor(){
    this.todos = [];
    this.newToDo = '';
    this.error = false;

  }
  //Define your addMore function here
  //Define your clearAll function here
addMore(){

}
clearAll(){

}
}

【问题讨论】:

  • 你需要创建一个新的 'todo' 对象并将其推送到 this.todos 中

标签: angular angular2-template


【解决方案1】:

角度活动跟踪器:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public done: boolean;
  public todos : any;
  public newToDo : string;
  public newToDoObj : any;
  public error : boolean;
  //public TODOS : Array;
  constructor(){
    this.todos = [];
    this.newToDo = '';
    this.error = false;
  }
  addMore(){
   this.todos.push({done : true, item : this.newToDo});
  }
  clearAll(){
  this.todos = [];
 }
}

【讨论】:

    【解决方案2】:

    public newToDo: string 是您输入的值所在的位置。 public todos: any(应该是public todos: Array&lt;string&gt;public todos: string[])保存你已经创建的所有任务。

    addMore() 函数在点击addActivity 按钮后被调用。所以现在在addMore() 函数中你应该使用newToDo 值并使用push() 方法将其推送到todos

    addMore() {
    this.todos.push(this.newToDo);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2021-06-11
      相关资源
      最近更新 更多