Dynamic Component selection in Angular2 [duplicate]

Solution 1:

  1. As the error says, a component must have an unique selector. If you want to bind component behavior to attribute selector like with [type='bool'] you'd have to use directives. Use selector='bool-field' for your BoolComponent.

  2. As the error says, your generic <field> component does not have an type attribute to bind to. You can fix it by adding an input member variable: @Input() type: string;

  3. You want to delegate the component template to a single component which receive a type attribute. Just create that generic component and other components which use it will only have to provide it, not its children.

Example: http://plnkr.co/edit/HUH8fm3VmscsK3KEWjf6?p=preview

@Component({
  selector: 'generic-field',
  templateUrl: 'app/generic.template.html'
})
export class GenericFieldComponent {
  @Input() 
  fieldInfo: FieldInfo;
}

using template:

<div>
  <span>{{fieldInfo.caption}}</span>

  <span [ngSwitch]="fieldInfo.type">
    <input  *ngSwitchWhen="'bool'" type="checkbox" [value]="fieldInfo.value === 1">  
    <input  *ngSwitchWhen="'text'" type="text" [value]="fieldInfo.value">  
    <select  *ngSwitchWhen="'options'" type="text" [value]="fieldInfo.value">
      <option *ngFor="let option of fieldInfo.options" >
        {{ option }}
      </option>
    </select>  
  </span>
</div>