1

I've got a form in angular that looks something like this (shortened version with its context removed):

<form [formGroup]="myForm">
    Name: <input type="text" formControlName="myName">
    <div>
        Gender: <input type="text" formControlName="myGender">
    </div>
</form>

what I want to accomplish is, by clicking on the gender input field, 2 radio buttons will be displayed and when clicking somewhere outside the gender formblock, the buttons disappear. for that I added a boolean variable to my components ts:

export class MyFormComponent implements OnInit {
  genderFocused: boolean = false;
  constructor(
  ) { }

  ngOnInit() {
  }
}

and tried something like this:

<form [formGroup]="myForm">
    Name: <input type="text" formControlName="myName">
    <div tabindex="-1" (focusout)="genderFocused = false">
        Gender: <input type="text" formControlName="myGender" (focus)="genderFocused = true">
        <label>Yes<input type="radio"></label>
        <label>No<input type="radio"></label>
    </div>
</form>

with that however, as soon as I click on one of the radio buttons, they immediately disappear. I looked around and have not found anything that helped me solve this issue.

I replaced the radio buttons with a text input field, and it behaved the exact same way. as soon as the input field within the div is focused, it disappears, which is not intended

Nahid Islam
  • 193
  • 1
  • 5
  • 15
Alan
  • 949
  • 8
  • 26

1 Answers1

2

You can use @HostListener to check if element is clicked outside and set a flag for the *ngIf condition:

 @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      this.clickedOutside = false;
    } else {
      this.clickedOutside = true;
    }
  }

As this answer suggested: Detect click outside Angular component

Ponpon32
  • 2,150
  • 2
  • 15
  • 26
  • this works in case of me clicking outside the entire component, but i just want to reduce this logic to the gender part of the form and not necessarily create a entire component arround that – Alan Sep 03 '19 at 08:49
  • OK, i'm not familiar with other way to do it, but for me it sounds like you have some functionality that related to some part of your DOM, so why shouldn't it be a specific component? – Ponpon32 Sep 03 '19 at 09:50
  • Now that i think about it, you are right. It should in fact be a component – Alan Sep 03 '19 at 11:04