Angular2:单击按钮时将文本框条目添加到范围

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

我是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(){

}
}
angular angular2-template
1个回答
0
投票

public newToDo: string是您输入值的所在。 public todos: any(应该是public todos: Array<string>public todos: string[])保存已经创建的所有任务。

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

addMore() {
this.todos.push(this.newToDo);
}
© www.soinside.com 2019 - 2024. All rights reserved.