Search code examples
angular2-templateangular2-formsangular2-components

custom child components in angularjs2


I currently developing angular2 application . I would like to know how to add html attributes to custom components.

For example lets assume i have custom dropdown component and am re-using in same page on many places. If i would like to develop some dropdowns as multiselect and some of them single select, Could you please tell me how to that. If I add mutiple on component template it is showing multiselect for all dropdowns. If I add to each component individually where am using, it is not understanding that "Multiple" attribute.


Solution

  • If i would like to develop some dropdowns as multiselect and some of them single select, Could you please tell me how to that.

    You should be using a boolean @Input decorator defined in your custom component (Question seems unclear and i am assuming that you didn't ask for an implementation logic of multi select and single select). Below gives an example of adding a multiselect check for your custom component and how parent should bind value to that attribute when rendering the custom component

    In your custom component.ts class

     @Input() multiple: boolean = false;
    

    In your custom html class

    <div *ngIf="!multiple"> 
    // render your single select html
    </div>
    
    <div *ngIf="multiple"> 
    //render your multiple select html
    </div>
    

    In the parent html while rendering the custom component (assumpe selector as the name of the component)

    // for multi select
    <selector [multiple]=true> </select>
    // for single select
    <selector [multipl]=false> </select>
    

    If your struggling to make a generic component supporting both single and multi select check this open source component ng-select

    If you have no idea on @Input and @Output decorators in angular2 check this article