In our AppComponent
let's add new string variable for user input.
export class AppComponent {
tasks = ['task 1', 'task 2', 'task 3', 'task 4', 'task 5', 'task 6', 'task 7'];
newTodo = '';
}
In our html app.component.html
, let's connect variable with <input>
via special type of binding - [(ngModel)]
<h1>My todo app</h1>
<div>
<div>
<h2>Add new</h2>
<div>
<input type="text" name="todo" [(ngModel)]="newTodo" placeholder="Add your task here">
<input type="button" value="Add">
</div>
</div>
<div>
<h2>List</h2>
<ul>
<li *ngFor="let task of tasks; let i = index">{{task}}</li>
</ul>
</div>
</div>
Now connect button Add
action click
with AppComponent
.
In html we need to add new special binding for functions - (click)
<h1>My todo app</h1>
<div>
<div>
<h2>Add new</h2>
<div>
<input type="text" name="todo" [(ngModel)]="newTodo" placeholder="Add your task here">
<input type="button" value="Add" (click)="addTodo()">
</div>
</div>
<div>
<h2>List</h2>
<ul>
<li *ngFor="let task of tasks; let i = index">{{task}}</li>
</ul>
</div>
</div>
In AppComponent
add function addTodo
that will be run after click
action.
This function should add state of newTodo
- user input - to existing Array tasks
using standard Array
function called push
.
Please remember to use this.
prefix in AppComponent
.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
tasks = ['task 1', 'task 2', 'task 3', 'task 4', 'task 5', 'task 6', 'task 7'];
newTodo = '';
addTodo() {
this.tasks.push(this.newTodo);
};
}
Last but not the least to create function in AppComponent
for cleaning input after
adding content to Array
.
First step is to create function called resetTodo
inside it set this.newTodo
to
empty string
.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
tasks = ['task 1', 'task 2', 'task 3', 'task 4', 'task 5', 'task 6', 'task 7'];
newTodo = '';
addTodo() {
this.tasks.push(this.newTodo);
};
resetTodo() {
this.newTodo = '';
}
}
Second step is to call this resetTodo()
function inside of out existing addTodo()
.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
tasks = ['task 1', 'task 2', 'task 3', 'task 4', 'task 5', 'task 6', 'task 7'];
newTodo = '';
addTodo() {
this.tasks.push(this.newTodo);
this.resetTodo();
};
resetTodo() {
this.newTodo = '';
}
}
Now you can test the code. :)
Ps. Please be aware that, if you do refresh manually browser - via F5 - all added data will go back to old state. This is because, we store data only in memory.
To store them with persistence - for longer time - we need other tools like databases.