Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Last active October 7, 2022 13:26
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 NetanelBasal/a3879b374d4df4b30ccb1b0c0f198fe4 to your computer and use it in GitHub Desktop.
Save NetanelBasal/a3879b374d4df4b30ccb1b0c0f198fe4 to your computer and use it in GitHub Desktop.
@Component({
template: `
<form [formGroup]="form">
<ng-container formGroupName="assignee">
<div>
<input
type="radio"
name="$case"
formControlName="$case"
value="userId"
/>
User
<input
type="radio"
name="$case"
formControlName="$case"
value="userGroupId"
/>
User Group
</div>
<ng-container [ngSwitch]="assignee.value.$case">
<ng-container *ngSwitchCase="'userId'">
<select name="userId" formControlName="userId">
<option ngValue="userA">User A</option>
<option ngValue="userB">User B</option>
</select>
</ng-container>
<ng-container *ngSwitchCase="'userGroupId'">
<select name="userGroupId" formControlName="userGroupId">
<option ngValue="groupA">Group A</option>
<option ngValue="groupB">Group B</option>
</select>
</ng-container>
</ng-container>
</ng-container>
<button>Submit</button>
</form>
`,
})
export class TaskFormComponent {
private fb = inject(FormBuilder);
form = this.fb.nonNullable.group({
name: '',
assignee: this.fb.nonNullable.group({
$case: 'userId',
}),
});
get assignee() {
return this.form.get('assignee') as FormGroup;
}
ngOnInit() {
const $case = this.assignee?.get('$case');
$case?.valueChanges.pipe(startWith($case.value)).subscribe(($case) => {
clearOneOf(this.assignee);
this.assignee.addControl(
$case,
this.fb.control('', Validators.required)
);
});
}
}
function clearOneOf(group: FormGroup) {
Object.keys(group.controls).forEach((key) => {
if (key !== '$case') {
group.removeControl(key);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment