In my dialog, there is a form component to which I pass a User
object. The intention is to prepopulate the form fields with values from this object when the form is opened after passing the object via a click event. Additionally, upon constructing the form component, an ajax call retrieves Role
objects to construct a dropdown select. The selected option in the dropdown should correspond to the role of the passed user object.
@Component({
inputs: ['selectedUser'],
outputs: ['editedUser'],
selector: 'user-form',
templateurl: 'user.form.themplate.html'
})
export class UserForm {
// The 'User' object includes login, firstName, lastName, email, and role properties
selectedUser: User;
roles: Role[];
controlForm: FormGroup;
editedUser: EventEmitter<User>
loginControl: AbstractControl;
firstNameControl: AbstractControl;
lastNameControl: AbstractControl;
roleControl: AbstractControl;
emailControl: AbstractControl;
constructor(fb: FormBuilder) {
this.controlForm = fb.group({
'loginControl': ['', Validators.required],
'firstNameControl': ['', Validators.required],
'lastNameControl': ['', Validators.required],
'roleControl': ['', Validators.required],
'emailControl': ['', Validators.compose(Validators.required,
MailValidator.validateMail]});
this.loginControl= this.myForm.controls['loginControl'];
this.firstNameControl= this.myForm.controls['firstNameControl'];
this.lastNameControl= this.myForm.controls['lastNameControl'];
this.emailControl= this.myForm.controls['emailControl'];
this.roleControl= this.myForm.controls['roleControl'];
// Fetch and populate 'this.roles' with Role object data
});
onSave() :void {
// Retrieve object from controlForm.value or create new object
this.editedUser.emit(this.selectedUser);
}
}
<form [formGroup]="controlForm">
<div class="field">
<input type="text"
[formControl]="loginContol">
</div>
<div class="field">
<input type="text"
[formControl]="firstNameControl">
</div>
<div class="field">
<input type="text"
[formControl]="lastNameContol">
</div>
<div class="field">
<input type="text"
[formControl]="emailContol">
</div>
<select [formControl]="roleContol">
<option *ngFor="let r of roles"
[selected] = "some expression to select the role from the selectedUser object"
>{{r.name}}</option>
</select>
<button type="save" [disabled]="!controlForm.valid" (click)="onSave()">Save</button>
</form>
Upon displaying the form, all fields should be populated with data from the selectedUser
object, including the role in the dropdown if applicable. Upon clicking the save
button, any changes made in the form should be used to create/update a User
object emitted by the event emitter. While it's possible to use ngModel
and ngForm
, this approach may not be ideal due to validator assignment complexities.