角度处理条件驱动形式

时间:2019-09-26 19:17:45

标签: html angular forms

我对Angular非常陌生,我使用的是模板驱动形式。 我有两个单选按钮形式的问题(如下所示),我的用例是,一旦用户根据他/她的回答回答了这两个问题,我就需要展示另一组问题。 因此,如果两个问题中的任何一个答案为“是”,那么我需要显示另一组问题。如果两个问题的答案都是“否”,那么我就不必显示另一组问题。请帮助实现它。

我的模板和component.ts文件如下所示。我尝试在条件下使用“ * ngIf” *ngIf="Question1 || Question2",但这不起作用,因为一旦第一个问题的答案为“是”,它就会显示带有“显示其余问题”文本的部分。请在下面查看我的示例代码。我希望当用户回答两个问题时,根据响应,仅显示带有文本“显示其余问题”或“不显示其余问题”的div。

<div class="form-group">
          <div class="form-group col-md-12">
            <label>Question 1?</label>
            <input type="radio" name="Question1" [(ngModel)]="Question1" value="yes">Yes
            <input type="radio" name="Question1" [(ngModel)]="Question1" value="no">No
          </div>
          <div class="form-group col-md-12">
            <label>Question 2?</label>
            <input type="radio" name="Question2" [(ngModel)]="Question2" value="yes">Yes
            <input type="radio" name="Question2" [(ngModel)]="Question2" value="no">No
          </div>
</div>  

 <div align="center" *ngIf="Question1 || Question2">
          Show rest questions
        </div>

 <div align="center" *ngIf="Question1 && Question2">
          Don't show rest questions
        </div>

下面是我的部分组件。

export class Component1 implements OnInit {
  public Question1:string;
  public Question2:string;
}

1 个答案:

答案 0 :(得分:3)

df1 <- structure(list(SAMPN = c(1L, 1L, 1L, 1L, 1L, 2L, 2L), PERNO = c(1L, 1L, 1L, 1L, 1L, 1L, 1L), loop = c(1L, 1L, 1L, 2L, 2L, 1L, 1L), car = c(3.4, 3, 4, 14, 5, 1, 9), bus = c(2.5, 2, 2, 1, 8, 5, 4), walk = c(1.5, 1, 5, 3, 2, 5, 3), mode = c(1L, 2L, 3L, 1L, 1L, 3L, 3L)), class = "data.frame", row.names = c(NA, -7L)) 会将所选值设置为字符串,如果您想将值设置为true / false,请尝试这样

value="yes"

然后您可以使用ngIf来显示其他类似的内容

<div class="form-group">
          <div class="form-group col-md-12">
            <label>Question 1?</label>
            <input type="radio" name="Question1" [(ngModel)]="Question1" [value]="true">Yes
            <input type="radio" name="Question1" [(ngModel)]="Question1" [value]="false">No
          </div>
          <div class="form-group col-md-12">
            <label>Question 2?</label>
            <input type="radio" name="Question2" [(ngModel)]="Question2" [value]="true">Yes
            <input type="radio" name="Question2" [(ngModel)]="Question2" [value]="false">No
          </div>
</div>
  

<div align="center" *ngIf="Question1 || Question2; else noQuestions "> Show rest questions </div> <ng-template #noQuestions> ..... </ng-template> 将在选择任何一个答案时变为true yes,或者您可以在两个答案中都显示其余答案,例如Question1 || Question2

demo ??

已更新!⚡⚡

将该值设置为true / false将会限制我们对所选案例的检查

Question1 && Question2

demo ??

相关问题