将自定义指令绑定到主机

Jac*_*rts 8 angular

我看起来很远但我似乎无法找到答案.我已经创建了一个指令,它工作正常,但我想动态地将它绑定到组件的主机.

例:

@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>
Run Code Online (Sandbox Code Playgroud)

我基本上想要删除a)显式设置myDirective和b)用一个元素包装模板的需要myDirective

Gün*_*uer 7

目前不支持此功能.

另见https://github.com/angular/angular/issues/8785

  • 显然,它将在 v15 中得到支持(请参阅上面链接的问题) (2认同)

Jan*_* K. 6

6年半后:

使用 Angular 15,您可以: https://angular.io/guide/directive-composition-api

在你的情况下:

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

myDirective一定是standalone: true(Angular15 中的另一个新事物)。含义 - 仍然没有FormControlName在你的组件内