Jacob Roberts
Jacob Roberts

Reputation: 1825

Bind custom directive to host

I've looked far and wide but I can't seem to find an answer. I've created a directive, which works fine, but I want to bind it to the host of a component dynamically.

Example:

@Directive({ selector: 'myDirective' })

@Component({ selector: 'myComponent',
    template: 'some content goes here...'
})
export class MyComponent {
    /* bind myDirective to host */
}

//when using myComponent, it should be
<myComponent></myComponent>
//not
<myComponent myDirective></myComponent>

I basically want to remove the need to either a) explicitly set myDirective and b) wrap the template with an element just to use myDirective

Upvotes: 24

Views: 13932

Answers (2)

Jan &#39;splite&#39; K.
Jan &#39;splite&#39; K.

Reputation: 2114

6 and half yars later:

With Angular 15 you can: https://angular.io/guide/directive-composition-api

In your case:

@Directive({ selector: 'myDirective', standalone: true })
export class ...
@Component({ selector: 'myComponent',
    template: 'some content goes here...',
    hostDirectives: [myDirective],
})
export class MyComponent {
}

Your myDirective must be standalone: true (another new thing in Angular15). Meaning - still no FormControlName inside your component 😫

Upvotes: 12

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657761

This is currently not supported.

See also https://github.com/angular/angular/issues/8785

Upvotes: 17

Related Questions