En nuestro archivo app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: string;
name: string;
email: string;
website: string;
hobbies: string[];
showHobbies: boolean;
constructor(){
this.title = '4funkies';
this.name = "Oscar";
this.email = "oscar@4funkies.com";
this.website = "http://oscarperiche.com";
this.hobbies = ['Música', 'Natura', 'Aventura'];
this.showHobbies = false;
}
toggleHobbies(){
this.showHobbies = !this.showHobbies;
}
newHobby(hobby){
//console.log(hobby.value);
this.hobbies.push(hobby.value);
hobby.value = '';
return false;
}
}
Y en nuestro app.component.html
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<img width="300" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Info</h2>
<ul>
<li>Name: {{name}}</li>
<li>Email: {{email}}</li>
<li>Web: {{website}}</li>
</ul>
<button (click)="toggleHobbies()">{{ showHobbies ? 'Hide Hobbies' : 'Show Hobbies' }}</button>
<div *ngIf="showHobbies">
<h2>Hobbies</h2>
<ul>
<li *ngFor="let hobby of hobbies">{{hobby}}</li>
</ul>
<form (submit)="newHobby(hobby)">
<input #hobby type="text" name="hobby" placeholder="Add a hobby">
</form>
</div>
En las últimas versiones de Angular-cli no se está agregando por defecto @angular/forms, ni tampoco @angular/http, así que lo tenemos que agregar manualmente ya que seguramente los necesitaremos. Para añadir @angular/forms abriremos el archivo app.module.ts y añadiremos la siguiente parte del código:
import { FormsModule } from '@angular/forms';
Y en el array de imports:
FormsModule
Quedando de la siguiente forma:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule // <-- import the FormsModule before binding with [(ngModel)]
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
