Angular 使用输入装饰器将对象的特定属性传递给子组件
假设我有一个对象客户,如下所示:Angular 使用输入装饰器将对象的特定属性传递给子组件,angular,typescript,Angular,Typescript,假设我有一个对象客户,如下所示: export class Customer { id: number; name: string; premium: boolean; address: string; country: string; } 在我的父组件中: /*** stuff declaration */ @ViewChild(ChildComponent) private childComponent: ChildComponent; custome
export class Customer {
id: number;
name: string;
premium: boolean;
address: string;
country: string;
}
在我的父组件中:
/*** stuff declaration */
@ViewChild(ChildComponent)
private childComponent: ChildComponent;
customer: Customer;
/*** Stuff */
@Input()
public customerSubpart : any;
/*
customerSubpart properties expected:
id, name, premium
*/
save() : void {
/* call service to save modifications */
}
子组件:
/*** stuff declaration */
@ViewChild(ChildComponent)
private childComponent: ChildComponent;
customer: Customer;
/*** Stuff */
@Input()
public customerSubpart : any;
/*
customerSubpart properties expected:
id, name, premium
*/
save() : void {
/* call service to save modifications */
}
我希望父模板上的单击事件在save()方法中保存对customerSubpart对象所做的修改。
我可以使用@ViewChild decorator来管理它,但是我只需要将customer
对象的子部分传递给customerSubpart
对象。
我真的需要创建一个新模型并将其注入客户模型(或使用继承)吗?或者有更干净的方法(最佳实践)?如果您想避免创建另一个模型,可以将其作为anon类型传入。例如,通过
{ id: customer.id, name: customer.name, premium: customer.premium }
然而,这不是一个好的实践,因为您失去了Typescript的打字优势
另一个可以满足您需要的解决方案是,根据必须发送的属性数量,为每个属性创建一个@Input()
。因此,例如,代替@Input()public customerSubpart:any代码>
你可以
@Input() id: number;
@Input() name: string;
@Input() premium: boolean;
第三种选择是将非子部分属性设置为可选属性,然后只发送所需的属性。所以你的班级会改成
export class Customer {
id: number;
name: string;
premium: boolean;
address?: string;
country?: string;
}
除非您强制停止,否则这仍然存在子组件意外更改后一属性的风险
我的建议是要么使用第二个选项,要么创建一个子模型,除非您不需要担心更改,在这种情况下,第三个选项也会起作用
祝你好运 这就是我在真实应用程序中拥有+100个模型属性的问题,我必须选择最可靠的方式。因此,为了符合Typescript约定,应选择第二个选项或子模型解决方案。输入装饰器将来应该由Angular团队提供更多特性。能够获得整个对象或仅部分对象。无论如何谢谢你!