Angular 18: Multiple select components with a ng-container share same observable dropdown list

Discussão em 'Angular' iniciado por Sannu, Dezembro 15, 2024.

  1. Sannu

    Sannu Guest

    I have a page with four dropdown lists. All four will have same choices.

    1. Can I have all four components share same Observable?
    2. How do I bind component variable to dropdown in ng-template.

    data.service.ts

    export class DataService {
    public getRefs(): Observable<string[]> {
    return of(['Ed Hochuli', 'Jerome Boger', 'Walk Anderson', 'Mike Carey']);
    }
    }


    app.component.ts

    export class AppComponent implements OnInit {
    onField1: string;
    onField2: string;
    tvRef: string;
    fourthRef: string;

    refList$: Observable<String[]>;

    constructor(private dataService: DataService) {}
    ngOnInit(): void {
    this.refList$ = this.dataService.getRefs();
    }

    onItemSelected(ref: string) {
    console.log('onItemSelected');
    }
    }


    app.component.html

    <ng-container
    [ngTemplateOutlet]="umpireSelectTemplate"
    [ngTemplateOutletContext]="{ controlName: 'onField1', label: 'On field 1' }"
    />
    <ng-container
    [ngTemplateOutlet]="umpireSelectTemplate"
    [ngTemplateOutletContext]="{ controlName: 'onField2', label: 'On field 2' }"
    />
    <ng-container
    [ngTemplateOutlet]="umpireSelectTemplate"
    [ngTemplateOutletContext]="{ controlName: 'tvRef', label: 'TV Ref' }"
    />
    <ng-container
    [ngTemplateOutlet]="umpireSelectTemplate"
    [ngTemplateOutletContext]="{ controlName: 'fourthRef', label: '4th Ref' }"
    />

    <ng-template
    #umpireSelectTemplate
    let-controlName="controlName"
    let-label="label"
    >
    <div>
    <label id="row">{{ label }}:</label>

    <div id="row">
    <select
    class="form-control"
    name="{{ controlName }}"
    [(ngModel)]="onField1"
    formControlName="{{ controlName }}"
    (change)="onItemSelected($event)"
    >
    <option *ngFor="let ref of refList$ | async" [ngValue]="ref">
    {{ ref }}
    </option>
    </select>
    </div>
    </div>
    </ng-template>


    Stackbliz project is available

    Continue reading...

Compartilhe esta Página