简体   繁体   English

如何传递Angular2组件的格式选项?

[英]How to pass formatting options for Angular2 component?

I have a very simple component like this 我有一个非常简单的组件

@Component({
  selector: "generic-select",
  template: `
 <select [(ngModel)]="target">
  <option *ngIf="target" hidden selected>{{target}}</option>
  <option *ngFor="let c of choices">{{c}}</option>
 </select>
`
}) export class SelectorComponent<T> {

  @Input()
  private choices: T[];

  @Input()
  private target: T;
}

And the problem is, that T is not always a primitive object like string or number, but is a complex object. 问题是,T并不总是像字符串或数字这样的原始对象,而是一个复杂的对象。 So, in such cases i want to pass something (i don't really know what) that tells how preview for T should look like. 因此,在这种情况下,我想传递一些内容(我并不真正知道),该内容告诉T预览的外观。

i want smth like 我想要像

<generic-select [choices]="choices" [target]="user.choice" [formatter]="(t:T) => t.name"></generic-select>

Not exactly what you asked for but this is a potential solution for the problem: 并非完全符合您的要求,但这是该问题的潜在解决方案:

If you're using TypeScript you can create classes that extend other classes . 如果使用TypeScript,则可以创建扩展其他类的类 If you were OK with having a convention for the display value field you could have this property on the common base class and use it instead of the generic type. 如果可以确定显示值字段的约定,则可以在公共基类上具有此属性,然后使用它代替泛型类型。

Obviously to work with primitive types they would need to be wrapped with a class as well. 显然,要使用基本类型,它们也需要被类包装。

Another approach if you want to support both primitives and custom types is to have two optional input attributes on the component, one for all primitives (as you have it now) and one for the common class type. 如果要同时支持原语和自定义类型,另一种方法是在组件上具有两个可选的输入属性,一个用于所有原语(如您现在所拥有),另一个用于公共类类型。 Then in your template display the value based on which input was provided. 然后,在模板中显示基于提供的输入的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM