Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

461
Views
How can i use *ngIf in the host of my Directive?

I want to create a Directive that removes/adds itself to the DOM like *ngIf would do. What i have so far is:

@Directive({
    selector: '[myDirective]',
    host: {
        '[hidden]': 'hidden',
    }
})
export class MyDirective {
  constructor(private myService : MyService) {
  }

  hidden() {
    return !this.myService.valid;
  }

But what i need is something like:

@Directive({
    selector: '[myDirective]',
    host: {
        '*ngIf': 'hidden',
    }
})
...

Sadly i can not use '*ngIf': 'hidden' in host of Directive. The error i get is:

Can't bind to 'ngIf' since it isn't a known property of 'button'.

Also '[ngIf]': 'hidden' is not working.

So, how can i use ngIf in a Directive?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

@Injectable()
export class MyService {
  valid = true;
}

@Directive({
  selector: '[myIf]'
})
export class MyIfDirective {
  constructor(private myService: MyService, 
        private el:ElementRef,
        private view:ViewContainerRef,
        private template:TemplateRef<any>) {
  }

  ngAfterViewInit(){
    if(this.myService.valid) {
      this.view.createEmbeddedView(this.template);
    }
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      Peek A Boo: <h2 *myIf>Hello</h2>
    </div>
  `,
})
export class App {
  constructor() {
  }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!