在角度2.0中尝试一个简单的表格

时间:2016-10-06 07:56:34

标签: angular typescript

我试图在一个简单的AngularJs 2示例的提交框中创建功能。但我无法找到办法。

这是我的app.component.html

<h1>
    {{title}}
</h1>

<h2>Contactos</h2>

<app-lista-contactos [listaContactos]="contactos" (seleccion)="onSelect($event)">
</app-lista-contactos>

<h2>Detalles</h2>
<app-detalle-contacto [(contacto)]="contactoSeleccionado" (reset)="limpiar()" (guardar)="onSubmit()">
</app-detalle-contacto>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Agenda';
  contactos: Persona[] = [
    {name: 'Pedro', email: 'pedro@gmail.com'},
    {name: 'Maria', email: 'maria@gmail.com'},
    {name: 'Juan', email: 'juan@gmail.com'}];

    contactoSeleccionado: Persona = new Persona();
    nuevoContacto = true;

    onSelect(contacto: Persona): void {
      this.contactoSeleccionado = contacto;
      this.nuevoContacto = false;
    }

    onSubmit(): void {
      if (this.nuevoContacto) {
        this.contactos.push(this.contactoSeleccionado);
        this.limpiar();
      }else {
        console.log('Contacto actualizado');
        console.log(this.contactoSeleccionado);
      }
    }

    limpiar(): void {
      this.contactoSeleccionado = new Persona();
      this.nuevoContacto = true;
    }

}

persona.ts

export class Persona {
    name: string;
    email: string;
}

detalle-contacto.component.html

<form (ngSubmit)="onSubmit()" #formulario="ngForm">
    <label id="nameID">Nombre</label>
    <input [(ngModel)]="contacto.name" name="name" id="nameID" required>
    <label id="emailID">Email</label>
    <input [(ngModel)]="contacto.email" name="email" id="emailID" required>
    <button type="button" (click)="onSubmit()" [disabled]="!formulario.form.valid">Guardar</button>
    <button type="button" (click)="limpiar()">Reset</button>
</form>

和detalle-contacto.component.ts

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { Persona } from '../persona';

@Component({
  selector: 'app-detalle-contacto',
  templateUrl: './detalle-contacto.component.html',
  styleUrls: ['./detalle-contacto.component.css']
})
export class DetalleContactoComponent implements OnInit {

  @Input()
  contacto: Persona = new Persona();

  @Output()
  reset = new EventEmitter<void>();
  guardar = new EventEmitter<Persona>();

  constructor() { }

  ngOnInit() {
  }

  limpiar(): void {
    this.reset.emit();
  }

  onSubmit(): void {
    this.guardar.emit();
  }

}

我知道应该有很多错误,因为我不理解100%的绑定概念。另外,我不知道如何真正实现Angular中的提交功能。

我很乐意收到任何帮助或建议。

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果您设置了Type="Submit"的提交按钮并在您的组件中添加了OnSubmit(),那么它将无法再进行设置。我是这样做的:

HTML中的

<button type="submit" label="Submit"></button>

在组件中:

onSubmit() {
   //whatever you want to do codewise here.
}