Sil*_*cer 9 angular2-inputs angular
我真的不明白对象绑定是如何工作的,所以如果有人能解释我是否可以在基类中使用@Input(),或者更好:装饰器和继承.例如,如果每个表单都应该接收一个客户,我有一个基类:
export class AbstractCustomerForm{
@Input() customer;
...
}
Run Code Online (Sandbox Code Playgroud)
然后我在实际组件中扩展此类:
export AwesomeCustomerForm extends AbstractCustomerForm implements OnInit{
ngOnInit(){
if(this.customer)
doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,客户永远不会被设置:(
更新
自2.3.0-rc.0起,正确支持继承
原版的
装饰器不是继承的.它们需要直接应用于用作组件的类.子类上的装饰器将被忽略.我已经看到它提到@Input()或者@Output()正在工作,如果只有超类有它们而子类没有.
我遵循的一个策略是这样的:
@Component({
selector: 'my-component',
template: `......`,
inputs: MyAbstractComponent.genericInputs
})
export class MyComponent extends MyAbstractComponent {
@Input() width: number = 200;
........
}
Run Code Online (Sandbox Code Playgroud)
哪里:
export abstract class MyAbstractComponent {
public static genericInputs : string[] = ['base'];
public base: String;
}
Run Code Online (Sandbox Code Playgroud)
因此,为MyComponent会得到base以及width绑定.事实上,我认为使用反思仍有改进的空间.
小智 5
即使在 Angular 4.2.4 中,它在开发模式下也能正常工作。但是在进行 prod build ( ng build -prod) 时它失败了:
ERROR in Template parse errors:
Can't bind to 'step' since it isn't a known property of 'app-textarea-step'.
1. If 'app-textarea-step' is an Angular component and it has 'step' input,
then verify that it is part of this module.
2. If 'app-textarea-step' is a Web Component then add
'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to
suppress this message.
Run Code Online (Sandbox Code Playgroud)
我的组件看起来像:
abstract class StepComponent {
@Input() step: BaseStep;
@Output() next = new EventEmitter<string>();
@Output() answer = new EventEmitter<Answer>();
}
abstract class SingleNextStepComponent extends StepComponent {
onSubmit(answer: string) {
// ConfirmStep heeft geen answer.
if (answer) {
this.answer.emit({ question: this.step.key, value: answer });
}
const step = this.step as SingleNextStep;
this.next.emit(step.next);
}
}
// Decorator inheritance works in standard build (ng build) but fails in production build (ng build -prod)
// Workaround: inputs element on @Component that contains the inputs.....
@Component({
selector: 'app-textbox-step',
templateUrl: './textbox-step.component.html',
inputs: ['step']
})
export class TextboxStepComponent extends SingleNextStepComponent { }
@Component({
selector: 'app-textarea-step',
templateUrl: './textarea-step.component.html',
})
export class TextareaStepComponent extends SingleNextStepComponent { }
Run Code Online (Sandbox Code Playgroud)
幸运的是,该解决方法有效。添加到 TextBoxStepComponent 的输入防止了这个失败,进入下一个,尚未提供“输入”。
但是“ng build”无需在@Component 装饰器上输入即可正常工作...
| 归档时间: |
|
| 查看次数: |
5797 次 |
| 最近记录: |