在Angular 4中将属性指令应用于组件
6446 观看
2回复
我创建了具有@Input()
绑定属性src的img-pop组件。我创建了具有@HostBinding()
属性src的authSrc指令。
@Component({
selector: 'img-pop',
template: `<img [src]="src"/>
<div *ngIf="isShow">
<----extra value----->
</div>`
})
export class ImgPopOverComponent implements OnInit {
@Input()
private src;
private isShow=false;
@HostListener('mouseenter') onMouseEnter() {
this.isShow= true;
}
@HostListener('mouseleave') onMouseLeave() {
this.isShow= false;
}
}
我有这样的指示。
@Directive({ selector: '[authSrc]' })
export class AuthSrcDirective implements OnInit {
@HostBinding()
private src: string;
constructor(private element: ElementRef) { }
ngOnInit() { }
@Input()
set authSrc(src) {
this.src = src+"?access_token=<-token->";
}
}
我想将两个功能结合在一起。
<img-pop [authSrc]="/api/url/to/image"></img-pop>
这样最终的url调用将是/ api / url / to / image?access_token = <-token->
但是会引发Can't bind to 'src' since it isn't a known property of 'img-pop'.
错误
如果我在概念上错了,请纠正我。
谢谢。
作者: Naveen raj 的来源 发布者: 2019 年 10 月 15 日回应 (2)
2像
根据核心贡献者的回答,无法使用设置组件的直接属性@HostBinding
。@HostBinding
总是直接绑定到DOM。因此,这是设计使然。这里是解释:
这可以按预期工作:
- 使用数据绑定在同一元素上的指令/组件之间进行通信比通过直接注入另一个数据要慢于直接通信
- 指令之间的绑定很容易导致循环。
因此,在您的情况下,这是可能的解决方案:
export class AuthSrcDirective {
// inject host component
constructor(private c: ImgPopOverComponent ) { }
@Input()
set authSrc(src) {
// write the property directly
this.c.src = src + "?access_token=<-token->";
}
}
有关更通用的方法,请参见this。
作者: Max Koretskyi aka Wizard 发布者: 21.05.2017 05:041像
仅针对与HTML匹配的选择器实例化指令,这些HTML静态地添加到组件模板中。
无法动态地从元素添加/删除指令。唯一的方法是添加/删除整个元素(例如使用*ngIf
来自类别的问题 :
- angular 如何查看我使用的Angular版本?
- angular AngularJS:如何清除URL中的查询参数?
- angular angular:根据模型中的布尔值切换按钮文本
- angular Angular 2:是否强制使用括号/方括号?
- angular 在最新的TypeScript(大概是v1.5)示例中,@(符号)是什么意思?
- angular2-directives 例外:无法绑定到“ ngFor”,因为它不是已知的本机属性
- angular2-directives 在Angular中全局注册指令
- angular2-directives 角度异常:无法绑定到'ngForIn',因为它不是已知的本机属性
- angular2-directives Angular2没有Renderer提供程序!(NgModel->令牌NgValueAccessor-> DefaultValueAccessor->渲染器)
- angular2-directives Angular 2 @Output没有任何作用
- angular-components 如何在组件模板中选择元素?
- angular-components Angular 2+中ngShow和ngHide的等价物是什么?
- angular-components 如何从父组件的CSS文件设置子组件的样式?
- angular-components 在AngularJS组件中将事件从父级传递到子级
- angular-components 当模板中存在ngIf时,如何确定Angular2组件是否已完全加载(包括ViewChilds)
- angular2-hostbinding AoT编译中的Angular2主机绑定问题
- angular2-hostbinding 在Angular 2中使用@HostBinding对模板子元素进行mouseenter / mouseleave时更改主机类
- angular2-hostbinding 角度2:获取HTML元素的位置
- angular2-hostbinding 使用angular2 @HostListener时onbeforeunload确认对话框不显示
- angular2-hostbinding 角@Hostbinding不起作用