简体   繁体   中英

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. So, in such cases i want to pass something (i don't really know what) that tells how preview for T should look like.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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