1

I am trying to display a div element if a checkbox is checked using ng-show. 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 --

<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 --

export class Person {

        constructor(
            public myCheckbox: boolean
        ) {  }
    }
Hoobs
  • 47
  • 2
  • 9
  • Possible duplicate of [What is the equivalent of ngShow and ngHide in Angular?](https://stackoverflow.com/questions/35578083/what-is-the-equivalent-of-ngshow-and-nghide-in-angular) – Lemmy Jan 08 '19 at 17:01
  • 1
    @Lemmy thanks for that! Helped me out – Hoobs Jan 08 '19 at 17:03

3 Answers3

2

Welcome to the community.

ng-show is a directive of the angularJS framework.

In Angular (note the capital 'A') we use the ngIf directive like this:

<div *ngIf="person.myCheckbox">
Keenan Diggs
  • 2,287
  • 16
  • 17
1

With angular, you should use ngIF

<div *ngIf="person.myCheckbox">

But you can do it just with 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>
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    @Pete I get it all the time with a React project..... "That is not how you do it in React...." but I been doing it with CSS for years, so lets add JavaScript overhead when CSS can do it all. :) – epascarello Jan 08 '19 at 17:09
  • much appreciated for showing me a different way to go about doing this! @epascarello – Hoobs Jan 09 '19 at 01:11
0

You simply have to use the *ngIf directive.

-- Your component.html file --

<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 --

export class Person {
    constructor(
        public myCheckbox: boolean
    ) {  }
}
Aidan Lovelace
  • 400
  • 2
  • 10