0

I have a parent component where we have a ng-select component with 10 options which i pass into ng-select from a parent. Also i have a checkbox.

my goal is to pass only 1 option when the checkbox is checked. Is there any chance to repeat default select's behavior when having select choosen i click the checkbox it automatically choose the only option according to my if condition.

Here's the example. https://stackblitz.com/edit/angular-8wvjvx?file=src%2Fapp%2Fapp.component.html

Expected result: when i click the checkbox ng-select changes the value according to my if condition;

Actual result: it doesn't. therefore i have a wrong value

2 Answers2

0

Use ViewChild

For example

Add this import to your parent component :

import { ViewChild } from '@angular/core';
import { HelloComponent } from './hello.component'

In parent component.ts :

@ViewChild('helloComponent') myHelloComponent: HelloComponent;

In parent component.html :

<app-select #helloComponent [options]="options" ></app-select>

You are then able to access to the properties of your child component from your parent.

You can for example declare a variable called selectedValue in your child component that will tell your select which value has to be selected (or has been selected by user input).

Hope it helps.

Flo
  • 936
  • 1
  • 8
  • 19
0

You have to do few changes to achieve what you need.

Set ngModel and ngValue properties to the select in parent component.

<select [(ngModel)]="checkedOption">

  <option *ngFor="let item of options" [ngValue]="item"> {{item.name}} </option>

</select>

Define checkedOption and items variables inside your parent component. Here checkedOption will catch the selected option in parent component and items will be passed to app-select component as an input. After doing changed your Parent Component is as follows.

export class AppComponent  {

  options: any;
  checkedOption: any;
  itemes: any;
  ...

  constructor () {
     this.options = this.defaultOptions;
     this.checkedOption = this.options[0];
     this.itemes = [this.checkedOption];
  }

  isChecked(isChecked) {

    this.itemes = isChecked ? [this.checkedOption] : this.options;
  }
}

Pass items to app-select component as follows.

<app-select [options]="itemes" ></app-select>

Find Forked StackBlitz.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45