简体   繁体   English

如何通过 function 在结构指令中创建嵌入式视图?

[英]How to pass function to createEmbeddedView in structure directive?

Template where directive is used:使用指令的模板:

<select>
  <ng-container *range="[1998, 2016]; let num; let fn = fn">
    <option (click)="fn()" [ngValue]="num">{{ num }} {{ fn | json }}</option>
  </ng-container>
</select>

Directive is:指令是:

@Directive({
  selector: "[range]"
})
export class RangeDirective {
  _range: number[];

  constructor(private vcr: ViewContainerRef, private tpl: TemplateRef<any>) {}

  @Input()
  set range(value) {
    this.vcr.clear();
    this._range = this.generateRange(value[0], value[1]);
    this._range.forEach(num => {
      this.vcr.createEmbeddedView(this.tpl, {
        $implicit: num,
        fn: submit
      });
    });
  }

  private generateRange(from, to) {
    let arr = [];
    for (let i = from; i <= to; i++) {
      arr.push(i);
    }

    return arr;
  }
}

Function is: Function 是:

let submit = () => {
  alert("Submit event");
};

My idea is to dynamically change handler click我的想法是动态更改处理程序点击

Your problem is here:你的问题在这里:

(click)="fn"

should be应该

(click)="fn()"

StackBlitz Example StackBlitz 示例

Edit编辑

The other issue that you are having is that browsers do not emit click events from <option> elements.您遇到的另一个问题是浏览器不会从<option>元素发出click事件。 There are two alternatives that I can think of:我能想到两种选择:

Option 1 - <select> change event:选项 1 - <select> change事件:

<select #select (change)="onChange(select.value)">
  ...
  <option value="a">A</option>
  ...
</select>

Unfortunately it is not possible to assign objects to <option> elements, therefore this approach does not help you because it is not possible to pass a function to the change event handler that is unique to each option.不幸的是,无法将对象分配给<option>元素,因此这种方法对您没有帮助,因为无法将 function 传递给每个选项唯一的change事件处理程序。

Option 2 - ngModelChange :选项 2 - ngModelChange

This approach should do what you want to do:这种方法应该做你想做的事:

<select ngModel (ngModelChange)="$event.fn(); onChange($event.value)">
  <option *range="[1998, 2016]; let num; let fn = fn" [ngValue]e="{ fn: fn, value: num }">{{ num }}</option>
</select>

StackBlitz Example StackBlitz 示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM