Vishnu Sharma
Vishnu Sharma

Reputation: 61

Angular2 : Add textbox entry to a span on click of button

I am totally new to Angular2 and would need your help for the below exercise. I need to add the entry from the textbox to the span on HTML. I have been requested to make changes only in the .ts file

I am not able to understand what needs to be added in the AddMore to ensure the entry from textbox is added on click of button beside the checkbox. Please help.

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

}
}

Upvotes: 1

Views: 2827

Answers (2)

Samadhan Bagal
Samadhan Bagal

Reputation: 31

Angular Activity Tracker :

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 = [];
 }
}

Upvotes: 3

web.dev
web.dev

Reputation: 359

public newToDo: string is where your input's value is. public todos: any (should be public todos: Array<string> or public todos: string[]) hold all of your tasks which has been already created.

addMore() function is being called after clicking on addActivity button. So now in addMore() function you should take newToDo value and push it to todos using push() method.

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

Upvotes: 0

Related Questions