What is the best way to leverage *ngIf within the host of my Directive?

I am working on creating a custom Directive that can dynamically add or remove itself from the DOM similar to *ngIf functionality. Here is what I have so far:

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

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

However, what I am aiming for is something like this:

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

Unfortunately, using '*ngIf': 'hidden' in the host of the Directive is throwing an error:

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

Similarly, trying '[ngIf]': 'hidden' is not achieving the desired result.

So, I am seeking advice on how to implement ngIf functionality within a Directive.

Answer №1

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

@Directive({
  selector: '[myVisibility]'
})
export class MyVisibilityDirective {
  constructor(private myService: MyService, 
        private element:ElementRef,
        private viewContainer:ViewContainerRef,
        private myTemplate:TemplateRef<any>) {
  }

  ngAfterViewInit(){
    if(this.myService.active) {
      this.viewContainer.createEmbeddedView(this.myTemplate);
    }
  }
}

@Component({
  selector: 'my-component',
  template: `
    <div>
      Show or Hide: <h2 *myVisibility>Greetings</h2>
    </div>
  `,
})
export class AppComponent {
  constructor() {
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the environment variable in an Angular application with user input

I'm currently in the process of developing an angular application that interacts with a REST API on the backend server. The URL for this server is currently set as an environment variable like so: export const environment = { production: false, lo ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...

What is the best way for me to access a certain web address?

I am working on setting up a routing mechanism in my Angular project, but I'm encountering a URL routing error. The application is unable to locate the specified URL. Below is the routing setup: navigation.ts { id: 'documentation-manag ...

Scoped variable in Typescript producing a generated Javascript file

I'm currently learning TypeScript through an online course, and I've encountered a problem that seems to be related to a VSCode setting. Whenever I compile app.ts, it generates the app.js file, but I immediately encounter a TypeScript error. It& ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly. Here is my template: <form class="forms-sample" #f="ngForm" (ngSubmit)="onS ...

Can a child component's constructor be enhanced with a fresh Injection class without the necessity of invoking super()?

While working with Angular, I encountered a situation where I have a child component inheriting from a parent component that injects multiple classes. I needed to extend the child component with an additional injection class that was not used in the parent ...

Leveraging ngOnChanges to determine the display of an overlay based on input alterations

Working with TS/Angular on a web application, I made the decision to refactor some code that handles displaying different overlays. Instead of having separate code for each overlay, I consolidated them into one "master overlay" and created a function withi ...

Automatically focus on the button

Encountering an issue where setting focus on a button upon the input key enter event is not working. While setting focus on inputs functions properly, using the same code on a button does not work at all. Sample HTML Component: <form [formGroup]=&apos ...

Why am I struggling to show the success message on my basic CRM Angular web application?

I'm facing an issue in my Basic Angular app where the success message is not being displayed even after writing the correct code. 1)app.component.html <h1 class="c1">{{title}}</h1> <div *ngIf="success_msg;" style=&q ...

Tips for showing solely the current page number within angular pagination

HTML : <!-- pagination controls --> <div class="pagination-container"> <pagination-controls (pageChange)="onPageChange($event)" [maxSize]="1" [id]="config.id" [directionLinks]="true">< ...

Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit { title = 'bucketList'; bucketList: BucketListItem[] = [ new BucketListItem( "Goa Trip", "Travel to Goa" ) ]; ngOnInit() { } onItemAdded(eventData) ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

Is there a way to sort through an array based on a nested value?

Within an array of objects, I have a structure like this: "times": [{ "id" : "id", "name" : "place", "location" : "place", "hours" : [ {"day": " ...

Guide to making a second request using an if statement inside an observable

The aim I have a requirement to make two HTTP requests. The first request should always be executed, and the second request should only be made if a certain condition is met. A signal needs to be emitted when: firstvar and secondvar are equal, and only ...

Exploring the routing hierarchy in Angular: Setting up parent and child

I'm completely new to Angular and I am in need of assistance with routing. The structure of my folders is as follows: https://i.sstatic.net/qNT0W.jpg There are two distinct layouts in my application - one for the login page, and another for the main ...

Does the Angular library "ngx-paypal" have the capability to process recurring payments?

For my Angular project, I am interested in utilizing the paypal library ngx-paypal. While I have experience with integrating javascript libraries, I specifically want to incorporate an Angular library such as https://www.npmjs.com/package/ngx-paypal Does ...

Tips for updating a single event in eventSource after it has been dragged and dropped in fullcalendar-angular

I have successfully set up the calendar using @fullcalendar/angular v4.2 and am fetching data from my backend API using eventSources. However, I am facing an issue with dragging events to a new date in the month view. <full-calendar #calendar ...

Angular 2 - One-Stop Form Component for Creating and Modifying

Seeking advice on how to efficiently reuse my Form Component. Data Model: class Contact { id?: String; name: String; } When a new Contact is created, the id is optional in the model as it doesn't exist at that point. When editing a Contac ...