Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created October 21, 2024 08:19
Show Gist options
  • Save Armenvardanyan95/788cf9774e4b7d27b9e252df778cc096 to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/788cf9774e4b7d27b9e252df778cc096 to your computer and use it in GitHub Desktop.
// instead of this:
@Component({
template: `
<form (submit)="onSubmit()">
<input type="text" name="name" [(ngModel]="form.name" />
<input type="email" name="email" [(ngModel]="form.email" />
<input type="number" name="age" [(ngModel)]="form.age" />
<button type="submit">Submit</button>
</form>
`,
})
export class FormComponent {
private readonly userService = inject(UserService);
form = {
name: signal(''),
email: signal(''),
age: signal(0),
};
onSubmit() {
const value = {
name: this.form.name(),
email: this.form.email(),
age: this.form.age(),
};
this.userService.addUser(value);
}
}
// do this:
@Component({
template: `
<form #form="ngForm" (submit)="onSubmit(form.value)">
<input type="text" name="name" [(ngModel)]="controls.name" />
<input type="email" name="email" [(ngModel)]="controls.email" />
<input type="number" name="age" [(ngModel)]="controls.age" />
<button type="submit">Submit</button>
</form>
`,
})
export class SubmitComponent {
private readonly userService = inject(UserService);
controls = {
name: signal(''),
email: signal(''),
age: signal(0),
};
onSubmit(value: User) {
this.userService.addUser(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment