A
A
Alena Khrenovskaya2018-04-17 10:32:51
Angular
Alena Khrenovskaya, 2018-04-17 10:32:51

@HostListener and CheckBox. Create your own directive. Any ideas?

Can I somehow listen for the checkbox click to use the directive on another element? app.component.html:

<div class="mat mat-app-background basic-container">
  <app-check-box-pass></app-check-box-pass>
</div>
<div>
  <p appNgxHide [ngxHide]="ngxHide">Test element</p>
  <mat-checkbox [(ngModel)]="ngxHide">
    <span *ngIf="!ngxHide">Скрыть текст</span>
    <span *ngIf="ngxHide">Показать текст</span>
  </mat-checkbox>
</div>

app.component.ts:
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  ngxHide = false;
}

ngx-hide.directive.ts:
import {
  Directive,
  ElementRef,
  // HostListener,
  Input
} from '@angular/core';

@Directive({
  selector: '[appNgxHide]'
})
export class NgxHideDirective {
  @Input() ngxHide: boolean;
  constructor(private el: ElementRef)  {
    if (this.ngxHide = true) {
      el.nativeElement.style.display = 'none';
    } else {
      el.nativeElement.style.display = '';
    }
  }

  // @HostListener('mouseenter') onMouseEnter() {
  //   this.hideTest(this.ngxHide);
  // }
  // @HostListener('mouseleave') onMouseLeave() {
  //   this.hideTest(false);
  // }
  // private hideTest(test: boolean) {
  //   if (test === true) {
  //     this.el.nativeElement.style.display = 'none';
  //   } else {
  //     this.el.nativeElement.style.display = '';
  //   }
  // }
}

Commented out is a check to see if the directive is receiving data correctly - and it works.
And the essence of the directive is that it should hide the element when the checkbox is selected.
Perhaps I was too confused and the solution is much simpler than I drew in my head, because two months ago I was not familiar with JS / TS / Angular, etc. I would be grateful even just for a link with information that would lead to a solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sasha Novik, 2018-04-23
@navix

If there are no additional conditions and you only need to show the block depending on the checkbox, then there is no need to create a directive, but the built-in ngModeland will suffice ngIf.

<p *ngIf="ngxHide">Test element</p>
  <mat-checkbox [(ngModel)]="ngxHide">
    <span *ngIf="!ngxHide">Скрыть текст</span>
    <span *ngIf="ngxHide">Показать текст</span>
  </mat-checkbox>

If you need to change the style of `display`, then the binding will be like this:
But ngIfit is preferable to use it, because it removes unnecessary blocks from the DOM and the view tree, and not just hides them through css.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question