我正在尝试理解将参数传递给具有1 - 必需,2 - 不是必需/可选的Component的概念。 可以说我有两个文件:
让我们说这是第一个包含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 });
}
}
所以这就是我要做的事情 - 在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
- 是可选的,而LocalStorage
和broadcaster
是必需的。
我现在找到的解决方案(但我不是很满意)-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
}
}
}
所以我需要有人澄清使用参数初始化组件的正确方法(必需/可选等等)或者我当前的解决方案 - 是正确做到这一点的唯一方法......?
答案 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