Lewis
Lewis

Reputation: 481

Angular 5 Dynamic Form based on a previous Form control

We use Angular 5 and we are trying to set up a dynamic form with options that show when Role isn't Admin. I am using ngIf and also trying to check the formcontrol for Role. I'm obviously not doing this right and starting to question if this can be done at all without calling a method in the ts file for the component to set a variable.

below is an excerpt of the form...

<div class="form-group">
            <span>Role*</span>
            <select class="form-control" formControlName="role" id="Role">
                <option *ngFor="let role of roles" [ngValue]="role">
                    {{role.Description}}
                </option>
            </select>
        </div>
        <div *ngIf="addUserFrm.controls.role.Description != 'Admin'" class="form-group">
            <span>Centre*</span>
            <select class="form-control" formControlName="centre" id="Centre">
                <option *ngFor="let centre of centres" [ngValue]="centre">
                    {{centre.Description}}
                </option>
            </select>
        </div>
        <div class="form-group" *ngIf="addUserFrm.controls.role.Description != 'Admin'">
            <span>Infrastructure*</span>
            <select class="form-control" formControlName="infrastructure" id="Infrastructure">
                <option *ngFor="let infrastructure of infrastructures" [ngValue]="infrastructure">
                    {{infrastructure.Description}}
                </option>
            </select>
        </div> 

many thanks in advance

Upvotes: 2

Views: 237

Answers (1)

Daniel B
Daniel B

Reputation: 8879

You can use the get(path: Array<string | number> | string): AbstractControl | null;, or more readable, formGroupName.get('formControlName') function to get the form control in a dynamic form.

Since you've only included an excerpt of your form, I can't say this exact snippet will work for sure, but you should get the idea.

<div *ngIf="addUserFrm.get('role').value.Description != 'Admin'" class="form-group">

Upvotes: 2

Related Questions