简体   繁体   English

如果选中复选框,如何显示div元素?

[英]How to show div element if checkbox is checked?

I am trying to display a div element if a checkbox is checked using ng-show. 如果使用ng-show检查复选框,我正在尝试显示div元素。 If the user does not have a telephone number, they check the checkbox and an input element should appear where they can enter their mailing address. 如果用户没有电话号码,他们会选中复选框,并且输入元素应显示在他们可以输入邮寄地址的位置。 However, switching between checked and unchecked values is having no effect at the moment. 但是,在已检查和未检查的值之间切换目前没有任何效果。

I have done two way binding on the element. 我已经对元素进行了双向绑定。

-- My component.html file -- - 我的component.html文件 -

<input type="checkbox" name="myCheckbox" [(ngModel)]="person.myCheckbox">
I don't have a telephone
<div ng-show="person.myCheckbox">
   Show when checked (telephone input)
</div>

-- Person.ts file -- - Person.ts文件 -

export class Person {

        constructor(
            public myCheckbox: boolean
        ) {  }
    }

Welcome to the community. 欢迎来到社区。

ng-show is a directive of the angularJS framework. ng-show是angularJS框架的指令。

In Angular (note the capital 'A') we use the ngIf directive like this: 在Angular中(注意大写'A')我们使用ngIf指令,如下所示:

<div *ngIf="person.myCheckbox">

With angular, you should use ngIF 使用angular,您应该使用ngIF

<div *ngIf="person.myCheckbox">

But you can do it just with CSS. 但你可以用CSS做到这一点。

 [name="myCheckbox"] + div { display: none; } [name="myCheckbox"]:checked + div { display: block; } 
 <input type="checkbox" name="myCheckbox" [(ngModel)]="person.myCheckbox"> I don't have a telephone <div> Show when checked (telephone input) </div> 

You simply have to use the *ngIf directive. 您只需使用*ngIf指令即可。

-- Your component.html file -- - 您的component.html文件 -

<input type="checkbox" name="myCheckbox" [(ngModel)]="person.myCheckbox">
I don't have a telephone
<div *ngIf="person.myCheckbox">
   Show when checked (telephone input)
</div>

-- Person.ts file -- - Person.ts文件 -

export class Person {
    constructor(
        public myCheckbox: boolean
    ) {  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM