Inform the Angular2 Directive about any modifications

I'm facing an issue that needs solving. I have a component containing a template.

ul(slider)
    li(*ngFor="let car of getRecentCars()")
        car-poster(bcg="{{car.recentBackgroundUrl}}",  image="{{car.indexImage}}")

Additionally, there is a slider directive present.

@Directive({
    selector: '[slider]'
})
export class sliderDirective{
    private el: HTMLElement;

    constructor(@Inject(ElementRef) elementRef: ElementRef) {
        this.el = elementRef.nativeElement;
        let _this = this;
        setTimeout(function(){
            $(_this.el).slick({
                infinite: false,
                slidesToShow: 1,
                slidesToScroll: 1
            });
        }, 0);

    }

}

The problem arises when the directive triggers before the component's data is available. Is there a way to delay the execution of the directive until the component finishes rendering?

Answer №1

One way to enhance your component or directive is by utilizing lifecycle hooks such as ngAfterViewChecked:

Check out this example:

@Directive({
    selector: '[slider]'
})
export class sliderDirective{
    private el: HTMLElement;

    constructor(@Inject(ElementRef) private elementRef: ElementRef) {
        this.el = elementRef.nativeElement;
    }

    ngAfterViewChecked() {
      $(this.el).slick({
             infinite: false,
             slidesToShow: 1,
             slidesToScroll: 1
      });
    }
}

To explore more about lifecycle hooks, refer to this documentation:

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

The error message "Type 'null' cannot be assigned to type 'Element | DocumentFragment'" occurs when using Nextjs/React createPortal

I am completely new to typescript. Currently, I'm working on a project that has a lot of pre-configured react components in JavaScript files (.js). My task now is to convert everything to TypeScript (.tsx) without triggering any ESLint errors. Unfort ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

What is preventing the route with parameters from functioning properly in Angular2?

I'm currently working on implementing a basic route with a parameter in Angular2. My setup involves Angular 2.0.0-rc.2 and angular router 3.0.0-alpha.7. I've mostly relied on the updated routing documentation available at https://angular.io/docs/ ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...

TypeScript encounters difficulty in locating the namespace within a Node.js dependency

I am faced with a situation where I have two node.js packages that each contain type declaration files. In package a, there is a namespace declared that I want to reference in package b. Package A index.d.ts declare namespace foo { export interface A ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

When running either the "ng serve" or "npm start" command, the browser does not open automatically as expected

After successfully generating a project using angular-cli following the installation steps, my project is currently running. However, I find it tedious that I have to manually open the browser and type http://localhost:4200/ to view the project. Is there ...

What is the location for adjusting the angular strictness flags that determine the level of strictness for strictTemplates?

Currently in the process of transitioning our application to strictTemplates, we are encountering a multitude of errors, some more significant than others. As a result, I decided to adjust the strictness of the angular type checker and came across these s ...

Using Math.min() or Math.max() syntax in Angular templates: A comprehensive guide

Within my pagination module, the following code snippet can be found: <p>Displaying {{(page-1) * pageSize}} to {{ Math.min((page-1) * pageSize + pageSize,tasks.length)}} out of {{tasks.length}}</p>. Unfortunately, it seems to be experiencing ...

What is the best way to resize a div located below a dynamic div in order to occupy the available space?

My website has a dynamic div1 and a scrollable table inside div2. I need the div2 to take up the remaining height of the window, while ensuring all divs remain responsive. I've tried using JavaScript to calculate and adjust the heights on window loa ...

I'm facing an issue where Typescript isn't recognizing Jest types

The Challenge Setting up a TypeScript project with Jest has been proving difficult for me. It seems that TypeScript is not recognizing the Jest types from @types/jest, resulting in an error message like this: Cannot find name 'test'. Do you nee ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Utilizing Angular to nest a simple component within another component and display it exclusively on a targeted page or parent component

Currently, I am developing a mobile app using Ionic 3 and have created 2 components - Dumb or presentation components. The first component is the <ion-navbar>, which contains another component called <header-wallet-badge></header-wallet-badg ...

A new interface property type that is customized based on the type property that is passed in

My dilemma lies in a generic interface with a field depending on the passed type. I'm exploring the possibility of having another field that can accept any type from the passed type. For instance: interface sampleObject { name: fullName age: n ...

Retrieving child component's data property in Vue 3 using TypeScript and Composition API

I have set up two components: a parent and a child. App.vue //Parent <template> <div class="common-layout"> <Container> <Header><center>Vue JS 3 (Composition API and )</center></Header> ...

Is it possible to use optional destructured arguments in a Typescript function?

Is there a way to create a function that accepts an optional object argument using destructuring in Typescript? myFunction({opt1, opt2}?: {opt1?: boolean, opt2?: boolean}) The error message "A binding pattern parameter cannot be optional in an implementa ...

Angular integration with Keycloak

Currently working on a project involving microservices in Spring Boot. I have implemented security for the backend using Keycloak with secret credentials and OAuth2. Testing this setup using Postman has been successful. However, when trying to build the U ...

After upgrading from angular version 7.0 to 8.0, I realized that the target in the tsconfig.json file remained unchanged

After running the command ng update @angular/cli @angular/core, I successfully updated my Angular 8 version. The updated versions are as follows: Angular CLI: 8.0.1 Node: 10.15.3 OS: linux x64 Angular: 8.0.0 ... animations, cdk, common, compiler, compiler ...

Guide to utilizing selenium for triggering Angular events (ng-click)

Attempting to invoke an angular ng-click through selenium is proving to be quite challenging. The focus lies on this particular snippet of javascript: <span class="col" ng-click="getHope(1,'pray','smile')">100%</span> This ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...