I have created an Angular reactive form where the labels are to be switched to via permissions. I want to handle these semantic switching via components by creating a component which would be responsible for taking data as @Input() and render that specific input tags. What is the proper way of handling this?
There is a parent master-form.component in which consists the with 'formGroup' and a sub-component named input-switch.component. I passed specific parameters onto the sub-component via @Input(). The sub-component consists of with field value and with formControlName, toggled with ngIf.
Here is the master-form.component html -
<form class="master-form" [formGroup]="masterForm" (ngSubmit)="submitData(masterForm)">
<label>My first field: </label>
<input-switch [setting]="'change'" [labelVal]="'first field value'" [formCtrl]="'firstField'">
</input-switch>
<label>My second field: </label>
<input-switch [setting]="'change'" [labelVal]="'second field value'"
[formCtrl]="'secondField'">
</input-switch>
<button type="submit" [disabled]="!masterForm.valid"></button>
</form>
Master-form component class -
class MasterFormComponent implements OnInit {
masterForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.masterForm = this.fb.group({
firstField: ['', Validators.maxLength(10)],
secondField: ['', Validators.maxLength(20)]
});
}
submitData(form) {
console.log('DONE!');
}
}
Input switch sub component class -
class InputSwitch {
@Input() setting ;
@Input() labelVal;
@Input() formCtrl;
}
Input switch sub component html -
<span *ngIf="setting !== 'change'">{{labelVal}}</span>
<input *ngIf="setting === 'change'" [formControlName]="formCtrl" />
There is an error being thrown mentioning the missing 'formGroup' in the input-switch.component and I am unable to set the form. What seems to be the problem in here? Is there any other way to achieve this functionality?