Angular 2在init()期间将参数传递给组件

时间:2017-06-16 18:58:49

标签: angular typescript

我正在尝试理解将参数传递给具有1 - 必需,2 - 不是必需/可选的Component的概念。 可以说我有两个文件:

app1.comp.ts

让我们说这是第一个包含App2Comp

的组件
export class App1Comp {

  // try 1
  // How the hell I pass my _properties variable to App2Comp ?
  constructor(private MyApp2 : App2Comp) {}


  // try 2
  constructor() {
      // Initialize the parameter inside the constructor
      // This gives an error that the call does not match the function's
      // Signature - that's because I never gave a value for:
      // LocalStorage & broadcaster ... ( which I can't - they don't need )
      this.MyApp2 = new App2Comp({  arg1 : 60 });

      // This didn't work either
      this.MyApp2 = new App2Comp(_properties={  arg1 : 60 });
  }
}

app2.comp.ts

所以这就是我要做的事情 - 在constractor

的标题中包含所有参数
export class App2Comp {

  // Doesn't work
  // mostly because an optional parameter doesn't come before required
  // ones
  constructor(public _properties? : any, private LocalStorage : LocalStorageService, private broadcaster : Broadcaster) {
  }

  // Also placing the _properties at the end of the required ones and
  // calling in app1.comp.ts with - also doesn't work:
  // this.temp = new App2Comp(_properties=this.properties);  

  // This type of writing, causing an error of:
  // LocalStorage & broadcaster are undefined 
  constructor(public _properties? : any, private LocalStorage? : LocalStorageService, private broadcaster? : Broadcaster) {
  }
}

例如,尝试将它与类似Python的类进行比较,您可以在init()

中混合必需的参数和可选参数
// Python example
def init(self, arg1, arg2, opt1=12, opt2=None)

所以我的_properties - 是可选的,而LocalStoragebroadcaster是必需的。

我找到的临时解决方案(app2.comp.ts)

我现在找到的解决方案(但我不是很满意)-is:

export class App2Comp {
  LocalStorage : any;
  broadcaster  : any;

  constructor(public _properties? : any) {
      this.LocalStorage = new LocalStorageService();
      this.broadcaster  = new Broadcaster;

      if ( _properties ) {
          // do some code here
      }
  }
}

所以我需要有人澄清使用参数初始化组件的正确方法(必需/可选等等)或者我当前的解决方案 - 是正确做到这一点的唯一方法......?

1 个答案:

答案 0 :(得分:3)

我建议传递属性作为标记中的输入。

在您的子组件中,声明@Input。例如:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'cool-component',
  template: `
    <p>{{JSON.stringify(properties)}}.</p>
  `
})
export class CoolComponent {
  // If an input is specified when the component is used it will
  // override this default.
  @Input() properties: any = { defaultKey: 'defaultValue' };
}

然后在您的父组件中,您只需通过标记将信息传递给子组件。

<cool-component [properties]="_properties"></cool-component>

有关更多信息,请查看: https://angular.io/guide/component-interaction