在Angular 8中,你可以使用@HostBinding
装饰器来代替host
来绑定属性到宿主元素上。下面是一个示例代码:
import { Component, Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'red';
}
@Component({
selector: 'my-component',
template: `
This is a custom directive
`
})
export class MyComponent { }
在上面的代码中,我们定义了一个名为 然后,我们在 请注意,在使用 希望这个示例能帮助到你!MyDirective
的指令。通过使用@HostBinding
装饰器,我们将style.backgroundColor
属性绑定到宿主元素上,这里的宿主元素是带有myDirective
属性的MyComponent
组件中使用了MyDirective
指令,通过将myDirective
属性添加到MyDirective
中设置了backgroundColor
属性为'red'
。
@HostBinding
时,你需要使用@Directive
装饰器来标记你的指令,并将其附加到你想要使用该指令的元素上。相关内容