如何在Angular 2中将@HostBinding与@Input属性一起使用? [英] How to use @HostBinding with @Input properties in Angular 2?
问题描述
(Angular 2 RC4)
使用 @HostBinding ,我们应该能够修改主持人,对不对?我的问题是,这也适用于@Input()属性吗?如果适用,正确的用法是什么?如果没有,还有其他方法可以实现吗?
我在这里做了一个Plunker来说明我的问题: https://embed.plnkr.co/kQEKbT/ >
假设我有一个自定义组件:
@Component({
selector: 'custom-img',
template: `
<img src="{{src}}">
`
})
export class CustomImgComponent {
@Input() src: string;
}
我想用属性指令来馈送src属性:
@Directive({
selector: '[srcKey]'
})
export class SrcKeyDirective implements OnChanges {
@Input() srcKey: string;
@HostBinding() src;
ngOnChanges() {
this.src = `https://www.google.com.mt/images/branding/googlelogo/2x/${this.srcKey}_color_272x92dp.png`;
}
}
为什么该指令不能更改自定义组件的[src]输入属性?
@Component({
selector: 'my-app',
directives: [CustomImgComponent, SrcKeyDirective],
template: `<custom-img [srcKey]="imageKey"></custom-img>`
})
export class AppComponent {
imageKey = "googlelogo";
}
谢谢!
@HostBinding()
不会创建与主机组件属性的属性绑定.不过,这可能值得一个错误报告;-)
我通过使用exportAs
和模板变量的变通办法使它工作,但这非常丑陋. https://plnkr.co/edit/TobNVn?p=preview
经过深思熟虑,我认为它应该可以工作.否则我根本不知道@HostBinding() src;
会做什么.
@HostBinding('attr.src') src;
或@HostBinding('class.src') src;
是更常见的情况.
(Angular 2 RC4)
With @HostBinding we should be able to modify properties of the host, right? My question is, does this apply to @Input() properties as well and if so, what is the correct usage? If not, is there another way to achieve this?
I made a Plunker here to illustrate my problem: https://embed.plnkr.co/kQEKbT/
Suppose I have a custom component:
@Component({
selector: 'custom-img',
template: `
<img src="{{src}}">
`
})
export class CustomImgComponent {
@Input() src: string;
}
And I want to feed the src property with an attribute directive:
@Directive({
selector: '[srcKey]'
})
export class SrcKeyDirective implements OnChanges {
@Input() srcKey: string;
@HostBinding() src;
ngOnChanges() {
this.src = `https://www.google.com.mt/images/branding/googlelogo/2x/${this.srcKey}_color_272x92dp.png`;
}
}
Why can't this directive change the [src] input property of the custom component?
@Component({
selector: 'my-app',
directives: [CustomImgComponent, SrcKeyDirective],
template: `<custom-img [srcKey]="imageKey"></custom-img>`
})
export class AppComponent {
imageKey = "googlelogo";
}
Thanks!
@HostBinding()
doesn't create property bindings to properties of the host component. That might be worth a bug report though ;-)
I got it working by a workaround with exportAs
and a template variable but that is quite ugly. https://plnkr.co/edit/TobNVn?p=preview
After some consideration, I think it should work. Otherwise I wouldn't know what @HostBinding() src;
would do at all.
@HostBinding('attr.src') src;
or @HostBinding('class.src') src;
are the more common cases.
这篇关于如何在Angular 2中将@HostBinding与@Input属性一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!