I'm just playing around with new angular typed forms api and couldn't figure out how to type FormGroup without declaring specific "FormInterface" witch has to match the original one.
Maybe I'm missing something or it's just impossible to do so.
I was able to make thing working correctly (example below), but what I'm not a fan of here is declaration of UserForm interface witch has no reference to User interface and has to be a mirror copy of it but with FormControl<> fields.
Is it possible in case like this to type FormGroup just with User interface?.
Full working example available on stackblitz
user.model.ts
export interface User {
firstName: string;
lastName: string;
email: string;
age: number | null;
}
user.service.ts
@Injectable()
export class UserService {
add(user: User): void {
console.log('Add user', user);
}
}
app.component.ts
interface UserForm {
firstName: FormControl<string>;
lastName: FormControl<string>;
email: FormControl<string>;
age: FormControl<number | null>;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
form: FormGroup<UserForm>;
constructor(private userService: UserService) {}
ngOnInit(): void {
this.form = new FormGroup({
firstName: new FormControl<string>('', { nonNullable: true }),
lastName: new FormControl('', { nonNullable: true }),
email: new FormControl('', { nonNullable: true }),
age: new FormControl<number | null>(null),
});
}
submitForm(): void {
this.userService.add(this.form.getRawValue());
}
}