首页 > 解决方案 > 如何正确地将函数传递给 Angular2/Typescript 中的自定义指令?

问题描述

我对 Angular 2 相当陌生。我正在从 AngularJS 升级我的应用程序,现在我正处于 UI/UX 开发的最后阶段。我有最后一个问题需要帮助。先感谢您。

当前计划

  1. 我有一个自定义指令TspFieldWidgetDirective,它接受多个输入,一个是 function @Input('onRefresh') public refresh: Function;
  2. TspFieldWidgetDirective元素可以在各种组件中使用,以重新设计标准表单字段
  3. 我将当前指令用作TspHeaderComponent模板内的选择框。
  4. 当用户更改选择框的值时,OnRefresh调用该函数来刷新应用程序以更新新公司的视图。

什么不工作

  1. 每当tspheaderComponentOnRefresh模板都加载到浏览器中时,它就会在函数上产生无限的调用循环,即oncompanyChange,当它仅在选择框更改值时才能调用一次。

  2. 当我从浏览器更改选择框的值时(在TspFieldWidgetDirective模板内 - (change)="refresh({'id': fieldData[fieldKey]})",会生成以下错误。 ERROR TypeError: _co.refresh is not a function

请注意

  1. 该功能在 Angular 5 中从未运行过,它在 AngularJS 中运行得非常好。
  2. 除了将函数作为输入传递给指令之外,其他一切都有效。

下面的代码片段:

tsp-header.component.ts

/*
    Method to change company of the company selector

    @param: id - string
    @return: none
 */
public onCompanyChange(id: string): void {
    if ((__env.debug && __env.verbose)) {
        console.log('Setting current_company_id to ' + id);
    }

    if (id !== undefined && id !== null)
    {
        // @TODO: Update user preference on server IF they have permission to change their default company
        this.cookies.set('preferences.current_company_id', id);
        this.core.app.current_user.preferences.current_company_id = id;
        this.core.initApp();

        this.router.navigate(['/app/dashboard']);
    }
}

tsp-header.html

<!-- company changer -->
<li>
  <tsp-field-widget 
      type="company-select" 
      [onRefresh]="onCompanyChange(id)" 
      [showAvatar]="true"
      [fieldData]="core.app.current_user.preferences"
      fieldKey="current_company_id" 
      [hideLabel]="true"
      [optionData]="core.app.session.base_companies">
  </tsp-field-widget>
</li>

tsp-field-widget.component.ts

// Component class
@Component({
  selector: 'tsp-field-widget',
  templateUrl: './templates/tsp-field-widget.html'
})
export class TspFieldWidgetComponent implements OnInit {
  public lang:any; // for i18n

  @Input() public type: string; // the field type
  @Input() public isRequired: boolean; // is the field required
  @Input() public isReadonly: boolean;

  @Input() public index: any; // index of ng-repeat
  @Input() public filterBy: any; // used in conjunction with ng-repeat
  @Input() public orderBy: any; // used in conjunction with ng-repeat
  @Input() public fieldData: any; // the record of ng-repeat
  @Input() public fieldKey: string; // the index of record - record[fieldKey]
  @Input() public placeVal: string; // the placeholder value of the field, usually used for selects and other dropdowns
  @Input() public pattern: string; // used for ng-pattern
  @Input() public prefix: string; // Text to display before title listings

  @Input() public recordId: any; // the ID of the record
  @Input() public label: string; // the label for the field for <label> tag
  @Input() public suffix: string; // sub label, usually placed below some label or title
  @Input() public optionData: any[]; // array of data used to populate selects or to store data values
  @Input() public showAvatar: boolean; // show the fields avatar
  @Input() public hideLabel: boolean; // show the fields <label>
  @Input() public showAdd: boolean; // show the add button (to add new record)
  @Input() public showTitle: boolean; // avatar type: show the name of the user
  @Input() public showDesc: boolean; // avatar type: show the name of the user
  // @Input() public isHighlighted:boolean; // default type: highlight text
  @Input() public numRows: string; // textarea: the number of rows of the text area
  @Input() public idKey: string; // select: the default ID key for option data - defaults to _id
  @Input() public titleKey: string; // select: the default title key for option data - defaults to title
  @Input() public descKey: string; // select: the default description key for option data - defaults to description

  @Input() public sliderType: string; // percent, amount or default, slider type
  @Input() public sliderMinValue: string; // slider type
  @Input() public sliderMaxValue: string; // slider type
  @Input() public sliderStepValue: string; // slider type
  @Input() public sliderOrientation: string; // slider type

  @Input() public dzOptions: any; // dropzone options
  @Input() public dzCallbacks: any; // dropzone callbacks
  @Input() public dzMethods: any; // dropzone methods

  @Input() public decimalPlaces: string; // tspFormat type

  @Input() public locale: string; // for dates and currency
  @Input() public format: string; // for dates
  @Input() public formatHours: string; // for dates
  @Input() public intervalMins: number; // for dates
  @Input() public owner: string; // used for module windows to determine the type of record to add

  @Input('onAdd') public add: Function;
  @Input('onEdit') public edit: Function;
  @Input('onToggle') public toggle: Function;
  @Input('onDelete') public delete: Function;
  @Input('onRefresh') public refresh: Function;

  constructor(private el: ElementRef,
    private cookies: TspCookiesService,
    public core: TspCoreService,
    private object: TspObjectService,
    public date: TspDateService) {
    this.lang = core.lang;
    this.date = date;
  }
}

tsp-field-widget.html

<div *ngIf="type=='company-select'">
  <select class="company-select" 
      class="form-control" 
      [(ngModel)]="fieldData[fieldKey]" 
      (change)="refresh({'id': fieldData[fieldKey]})" 
      data-parsley-trigger="change">
    <option [selected]="x[idKey] === fieldData[fieldKey]" *ngFor="let x of optionData" [ngValue]="x[idKey]">
      {{x[titleKey]}}
    </option>
  </select>
</div>

标签: angulartypescriptangular2-templateangular2-directivesangular2-components

解决方案


Angular 的变更检测在视图初始化期间已经被触发。但此时 refresh() 可能仍为空/未定义。

我建议不要直接调用 'refresh()' 而是一个可以检查 refresh() 是否已经传入的包装方法。

在你的tsp-field-widget.html中有这样的东西:

(change)="doRefresh({'id': fieldData[fieldKey]})"

这在你的tsp-field-widget.component.ts

private doRefresh(object: any): void {

    if(refresh) {
       refresh(object);
    }

}

这样,您可以确保仅在刷新已存在时才调用它。


推荐阅读