Angular 2:用作@Input-属性

Angular 2: Function as an @Input-Property

你可以在这里看到我的Plunk。 在这个非常简单的示例中,我传递了一个函数

   _ => {
    console.log(number);
  }

使用@Input 属性 到子组件。我的父组件如下所示:

@Component({
    selector: 'my-app',
    template: `

                <child [func]="getFunction(3)">
                </child>
                <button type="button" (click)="startChangeDetection()">
                  Start change detection
                </button>
    `,
    directives : [Child],
    styles:[`

          .titles {
                    color:#0099FF
             }
            .child-style {
                    background-color:#00ffff
            }
            ` ],
})
export class CarComponent {
    startChangeDetection()
    {

    }
    getFunction(number)
    {
      return _ => {
        console.log(number);
      }
    }
}

该按钮除了触发另一轮变化检测外什么都不做(回调函数中没有实现。 但是,我的更改检测始终将我的输入识别为更改,但它从不 更改。 这是我的子组件:

@Component({
    selector: 'child',
    template: `
                <h2>Child Component</h2>
             `,
    inputs: ['func']
})
export class Child {

    private func;

    ngOnChanges(changes)
    {
      console.log(changes.func.previousValue.toString());
      console.log(changes.func.currentValue.toString());
    }

}

您可以看到,在 ngOnChanges 中,我将函数记录到控制台。但是记录的值(显然)永远不会改变,所以输出总是:

function (_) {
                        console.log(number);
                    }
function (_) {
                        console.log(number);
                    }

为什么 Angular 甚至调用 ngOnChanges?为什么它认为有任何变化?

此方法 returns 每次调用 getFunction 不同的函数实例。

getFunction(number)
{
  return _ => {
    console.log(number);
  }
}

因为 <child [func]="getFunction(3)">,每次更改检测 运行 时都会调用 getFunction

绑定到函数通常不是最好的主意。如果您以这种方式移出函数创建,则每次都会返回相同的函数实例,并且 Angular 更改检测不会将其识别为更改:

myCallback = _ => this.myCallBack(number) {
  console.log(number);
}

getFunction(number)
{
  return this.myCallback;
}

我没有看到任何异常。更改检测被调用两次。

  1. 第一次因为子组件在汽车组件内渲染。组件树已更改。

  2. 第二次,因为当您将函数 getFunction 作为 getFunction(3) 传递给输入时,函数 getFunction 被调用。这相当于输入值的变化,因此触发变化检测周期。