Skip to content

Instantly share code, notes, and snippets.

@casgin
Created March 15, 2019 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casgin/92f6d454b1a994a73b125c63eca5c37c to your computer and use it in GitHub Desktop.
Save casgin/92f6d454b1a994a73b125c63eca5c37c to your computer and use it in GitHub Desktop.
Esempio NgForm
import { Component, OnInit } from '@angular/core';
// --- Importo NgForm
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-root-form1',
template: `
<!--
Crero il form dove specifico con una TemplateReferenceVariabile
che si tratta di ngForm, in questo modo attivo il oneWay data binding
-->
<form #f="ngForm" (submit)="add(f)">
<!--
con [ngModel] associo questo campo di input
ad una property di una interfaccia associata
la porperty sarà qualle definita nell'attributo name
-->
<input
type="text"
placeholder="Add User name"
[ngModel]="user?.label"
name="label"
>
<input
type="number"
placeholder="Add User age"
[ngModel]="user?.age"
name="age"
>
<button type="submit">
{{user ? 'Edit' : 'Add'}}
</button>
</form>
<li *ngFor="let user of users"
(click)="setActive(user)"
>
{{user.label}} ({{user.age}})
</li>
`,
styles: []
})
export class AppComponentForm1Component {
users: User[] = [];
user: User;
add(form: NgForm) {
this.users.push(form.value as User);
}
setActive(user: User) {
this.user = user;
}
}
// User interface
interface User {
label: string;
age: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment