Created
March 15, 2019 05:35
-
-
Save casgin/92f6d454b1a994a73b125c63eca5c37c to your computer and use it in GitHub Desktop.
Esempio NgForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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