如何在Angular 2中使用@HostBinding和@Input属性?

Lau*_*ens 23 angular

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

我想用一个属性指令来提供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`;
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么这个指令不能改变自定义组件的[src]输入属性?

@Component({
  selector: 'my-app',
  directives: [CustomImgComponent, SrcKeyDirective],
  template: `<custom-img [srcKey]="imageKey"></custom-img>`
})
export class AppComponent {
  imageKey = "googlelogo";
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Pii*_*zei 65

你需要像这样组合装饰器:

@HostBinding('class.active') @Input() active: boolean = false;

  • 如果我的输入是一个对象并且我想绑定该对象的属性,我该怎么办? (3认同)

Sys*_*emR 13

如果你的@Input是一个对象,你可以这样做:

@Input() settings: Settings;

@HostBinding('class.active')
public get isActive(): boolean {
  return this.settings.isActive;
}
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 6

@HostBinding()不会创建属性绑定到主机组件的属性.这可能值得一个bug报告;-)

我通过一个变通方法exportAs和一个模板变量来实现它,但这非常难看.https://plnkr.co/edit/TobNVn?p=preview

经过一番考虑,我认为它应该有效.否则我不知道@HostBinding() src;会做什么.

@HostBinding('attr.src') src;或者@HostBinding('class.src') src;是更常见的情况.

  • 谢谢你的快速反应.我在这里做了一个bug报告:https://github.com/angular/angular/issues/10499 (2认同)

dab*_*eng 6

  1. 使用输入属性声明主机绑定属性。

    @HostBinding('attr.aaa') @Input() aaa: boolean = false;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将主机绑定属性设置为输入属性

    @Input() aaa: string;
    @HostBinding('attr.bbb') ccc: string;
    
    ngOnInit(){
      this.ccc = this.aaa;
    }
    
    Run Code Online (Sandbox Code Playgroud)