1
votes

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?

1

1 Answers

0
votes

You can go through this blog. It mentions how you can handle child components within a form using ControlValueAccessor interface.

Nested Reactive Forms Using ControlValueAccessors

This is complex, but you can try it.

Also you can create two separate components, each having different form elements and toggle them using *ngIf. Breaking it in component/directive will require inserting in every form field. Model binding needs to be handled correctly, keeping in mind the ngModel is present in the parent controller. If not handled properly this can increase code complexity.

Depending on your requirement choose a way to proceed.