NgIf-Else 条件无法正常工作

NgIf-Else condition does not work properly

我是 Angular 8 的初学者,我的部分代码有一些困难。 事实上,我正在尝试在 a 中使用 ngIf Else 条件来根据我检索的值显示按钮。

<div class="form-group">  
    <div class="row">        
        <div class="input-group col-12 md-12">
            <div class="input-group-prepend">
                <label for="situation" class="input-group-text">Current Situation</label>
            </div>
            <select class="custom-select" id="situation" formControlName="situation" name="situation" [(ngModel)]="employed">
                <option value="employed" name="employed">Employed(including unpaid family workers and apprentices)</option>
                <option value="employed" name="employed">Employed but is temporarily absent(leave without pay, parental leave etc.)</option>
                <option value="unemployed"> Unemployed, looking for work(job seekers)</option>
                <option value="retired"> Retired </ option >
                <option value="unable">Unable to work(disability)</option>
                <option value="domesticWorker"> Woman or man working in their own household(domestic worker)</option>
                <option value="student"> Pupil or Student</option>
                <option value="preschool"> Pre - school child</option>
                <option value="other"> Other(specify) </ option >
            </select>
        </div>
    </div>
</div>

<ng-container *ngIf="employed; then trueCondition else elseTemplate" >
    <div class="btn-toolbar">
        <button class="btn btn-primary" data-toggle="modal" data-target="#householdsFormModal2" data-dismiss="modal" type="button">NEXT</button>
    </div>
</ng-container>
<ng-template #elseTemplate>
    <div class="btn-toolbar">
        <button class="btn btn-primary" data-toggle="modal"
                data-dismiss="modal" type="button"
                [disabled]="householderForm.invalid">SUBMIT</button> 
    </div>
</ng-template>

当我选择前两个选项时,我的按钮设置为下一步,但是当我选择其他选项时,它停留在下一步状态而不是提交

您正在使用 ngIfThen 语法,这也需要 trueCondition 作为模板。

参见Angular NgIf documentation

<ng-container *ngIf="employed == 'employed'; then trueCondition else elseTemplate"></ng-container>
<ng-template #trueCondition>
    <!-- Content if true -->
</ng-template>
<ng-template #elseTemplate>
    <!-- Content if false -->
</ng-template>

我想你想要的是 ngIf 语法,即 *ngIf="employed == 'employed'; else elseTemplate.

<ng-container *ngIf="employed == 'employed'; else elseTemplate">
    <!-- Content if true -->
</ng-container>
<ng-template #elseTemplate>
    <!-- Content if false -->
</ng-template>

此外,请注意不要将您的 ngModel 命名为 employed 与其实际值混淆,可以是 string 与值 employed.

名为 employedngModel 将始终是 "truthy",因此请务必检查 employed == 'employed'