Angular 4 / ionic 3自定义属性指令不起作用

时间:2017-10-31 07:30:09

标签: angular typescript ionic-framework ionic3 angular2-directives

您好我正在尝试专注于搜索输入字段。我为此创建了一个指令。它已经从directives.module.ts导出。我还将directives.module导入到app.module.ts中。每当我尝试在ion-searchbar中使用该指令时,它都会出现以下错误。我不知道我错过了什么。

Can't bind to 'focuser' since it isn't a known property of 'ion-searchbar'.
  

directives.module.ts

import { NgModule } from '@angular/core';
import { FocuserDirective } from './focuser/focuser';
@NgModule({
    declarations: [FocuserDirective],
    imports: [],
    exports: [FocuserDirective]
})
export class DirectivesModule {}
  

focuser.ts

import {Directive, Renderer, ElementRef} from "@angular/core";

/**
 * Generated class for the FocuserDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
  selector: '[focuser]' // Attribute selector
})
export class FocuserDirective {

  constructor(public renderer: Renderer, public elementRef: ElementRef) {}

    ngOnInit() {
      //search bar is wrapped with a div so we get the child input
      const searchInput = this.elementRef.nativeElement.querySelector('input');
      setTimeout(() => {
        //delay required or ionic styling gets finicky
        this.renderer.invokeElementMethod(searchInput, 'focus', []);
      }, 0);
    }

}
  

app.module.ts

import { DirectivesModule } from '../directives/directives.module';


export function provideSettings(storage: Storage) {

  return new Settings(storage, {
    option1: true,
    option2: 'Ionitron J. Framework',
    option3: '3',
    option4: 'Hello'
  });
}

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AutoCompleteModule,
    CalendarModule,
    DirectivesModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  exports: [
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    Api,
    User,
    SplashScreen,
    StatusBar,
    Constants,
    { provide: Settings, useFactory: provideSettings, deps: [Storage] },
    // Keep this to enable Ionic's runtime error handling during development
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    BoxProvider,
    TellersProvider,
    CheckoutProvider,
    CommonProvider,
  ]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:4)

您需要从DirectivesModule文件中完全删除app.module.ts模块,并在imports page's module内使用directive删除focuser模块 <script language="javascript"> function changeQty(qty){ var currentQty = document.getElementById('lblSalePrice').value; currentQty = currentQty + qty; document.getElementById('lblSalePrice').value = currentQty; } </script> <a style="color:#000;text-decoration: none" href="javascript:changeQty(1)"> <img src="images/add.png" border="0" title="UpArrow" /> </a> <a style="color:#000;text-decoration: none" href="javascript:changeQty(-1)"> <img src="images/add.png" border="0" title="DownArrow" /> </a> }})。