reusable component in angular

不羁的心 提交于 2021-02-10 22:20:34

问题


im trying to create my own select component

so the final result will be like that

in app.components.html for example

<div>
    <app-my-select [(ngModel)]="val">
        <app-my-option value="1" >one</app-my-option>
        <app-my-option value="2" >two</app-my-option>
        <app-my-option value="3" >three</app-my-option>
        <app-my-option value="4" >four</app-my-option>
    </app-my-select>
</div>

in my-select.component.html

<input (click)="openPanel()" class="select-value-container" readonly (keydown)="keyDown($event.key)"
       type="text" (blur)="onTouched()" (input)="onInputChange(origin.value)" [disabled]="disabled" [value]="options[index]" #origin>
    
<ng-template #panelTemplate>
  <div class="drop-down">
    <ng-container
      [ngTemplateOutlet]="myOptionTemplate"
      [ngTemplateOutletContext]="{optionSelected = 'optionSelected'}">
    </ng-container>
  </div>
</ng-template>

-> I used ng-template for select drop down because i want to pass it to CDK overlay and it works fine

my-select.component.ts

...
  @ContentChild(NgOptionTemplateDirective) myOptionTemplate: TemplateRef<any>;
...

my-option.component.html

<ng-template ng-option-tmp let-optionSelected>
    <ng-content></ng-content>
</ng-template>

the issue is how I can project my-option templates inside select component

in another way what i should write in " ngTemplateOutlet " directive

and the final question is how I can get a reference to all my-option templates in my-select component is it bu using '@ContentChildren'

Updated Quesion:

how I can get reference to options templates as QueryList of TemplateRef.
because for now I can get reference to them as QueryList of MyOptionComponent

I have another suggestion by using div inside my-option html instead of ng-template so I can use just ng-content and not ng-template-outlet

but the new question will be how I can pass optionSelected event to parent component I mean my-select component without using ng-template

来源:https://stackoverflow.com/questions/63511926/reusable-component-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!