Angular: Show inputs on form based on previous selection or input

1k views Asked by At

I'm using VMware's clarity-seed repo and I'm attempting to build an input form that prompts for additional related information. For example, the form has a pull down list selection for authentication type. Depending on the type I may need more information and that information is specific to the type. "None" auth needs no more information. "Basic" requires user and password combo while "OAuth" wants an API token.

I tried using ng-switch with no luck - the text is showing for both options despite the selection (I'm just using text for now and will add the sub-form details later).

I take it that my use of the form fields is wrong somehow, but I can't figure out why and how.

<form>
<section class="form-block">
    <span>New Endpoint</span>
    <div class="form-group">
        <label for="endpoint.name" class="required">Name</label>
        <input type="text" id="endpoint.name" size="45">
    </div>
    <div class="form-group">
        <label for="endpoint.id">Description</label>
        <input type="text" id="endpoint.id" size="45">
    </div>
    <div class="form-group">
        <label for="endpoint.url" class="required">URL</label>
        <input type="url" id="endpoint.url" placeholder="http://endpoint.co/api" size="35">
    </div>
    <div class="form-group">
        <label for="endpoint.authType">Authentication</label>
        <div class="select" class="required">
            <select id="endpoint.authType">
                <option>None</option>
                <option>Basic</option>
                <option>OAuth</option>
            </select>
        </div>
    </div>
    <div ng-switch="endpoint.authType">
        <div ng-switch-when="Basic">
            <h1>Another form for Basic credential set</h1>
        </div>
        <div ng-switch-when="OAuth">
            <h1>Another form for OAuth token</h1>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</section>

1

There are 1 answers

1
Vega On BEST ANSWER

You can use the new syntax for *ngIf - then ;else:

<div *ngIf="endpoint.authType === 'Basic'"; then basic; else auth>
        <ng-template #basic>
            <h1>Another form for Basic credential set</h1>
        </ng-template>
        <ng-template #auth>
            <h1>Another form for OAuth token</h1>
        </ng-template>
</div>

Docs

If you have more than two values, you can still use ngSwitch:

<div [ngSwitch]="conditionExpression">
   <ng-template [ngSwitchCase]="case1Exp">...</ng-template>
   <ng-template ngSwitchCase="case2LiteralString">...</ng-template>
   <ng-template ngSwitchDefault>...</ng-template>
</div>

Docs