Angular2 Final:HostBinding不再工作了

时间:2016-10-15 03:34:01

标签: angular

这是我主持绑定到名为"禁用"的按钮属性的方式。在ng2-RC4中的父组件上:

@Component({
    selector: "nav-next",
    template: `
    <div class="nav-next-directive" (click)="onClick($event)">
        <button color="primary" class="primary" [attr.disabled]="disabled">
            <ion-spinner *ngIf="ngIf === true" icon="lines"></ion-spinner>
            {{buttonTitle}}
        </button>
    </div>`
})

export class NavNextDirective {

    @HostBinding("attr.disabled"); 
    @Input() isValid: boolean; 

这不再起作用了,(ngc抱怨)我现在通过改变上面部分到达了一半:

@HostBinding("attr.disabled") isValid: boolean = true;
@Input() isValid: boolean;

然而ngc说:

Can't bind to 'isValid' since it isn't a known property of 'nav-next'.
1. If 'nav-next' is an Angular component and it has 'isValid' input, then verify that it is part of this module.
2. If 'nav-next' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
 ("
    <ion-list>
        <nav-next (click)="save()"
                  [ERROR ->][isValid]="goalForm.valid"
                  [serverWaiting]="serverWaiting"
                  button"): GoalDefineAmountComponent@30:18

有关Hostbinding现在如何运作的任何想法吗?

1 个答案:

答案 0 :(得分:1)

错误与主机绑定无关。这是关于试图使用它的组件不知道的NavNextDirective

NavNextDirective需要与使用它的组件位于同一范围中。这意味着您可以在同一模块中声明它

@NgModule({
  declarations: [ NavNextDirective, ComponentThatUsesNavNextDirective ]
})
class SomeModule {}

或者如果NavNextDirective将由不同的模块使用,则在其自己的模块或共享模块中声明和导出该指令,并将该模块导入具有使用该指令的组件的模块中< / p>

@NgModule({
  declarations: [ NavNextDirective ],
  exports: [ NavNextModuleDirective ]
})
class NavNextModule {}

// OR

@NgModule({
  declarations: [ NavNextDirective ],
  exports: [ NavNextModuleDirective ]
})
class SharedModule {}

然后导入

@NgModule({
  imports: [ SharedModule ]
  declarations: [ ComponentThatUsesNavNextDirective ]
})
class ModuleWithComponentThatUsesNavNextDirective {}

这是一种误解我认为有些人只需要将组件/指令导入到app模块中,所有其他模块都可以使用它。事实并非如此

@NgModule({
  imports: [ ModuleWithComponentThatUsesNavNextDirective ],
  declarations: [ NavNextDirective ] 
})
class AppModule {}

此处,ModuleWithComponentThatUsesNavNextDirective无法看到NavNextDirective中声明的AppModule。它要么需要声明指令本身,要么imports指定exports指令的模块。但请注意,组件只能由任何模块声明一次。因此,如果组件要被许多模块使用,那么您应该专门为该组件创建一个模块,或者创建一个包含大量可重用组件的共享模块。