Search code examples
angularangular-componentsangular-library

Angular 2 + reset component library control


I have created an angular component library that I am installing via npm into my applications.

I have a drop down that gets populated and used fine...the problem comes when I want to "reset" the component library controls to do a fresh selection.
I'm not sure how to do this?

This is my component library html for drop down control..

  <select [(ngModel)]='thisControl' name="nameControl" id="idControl" 
      (ngModelChange)="updateControl(thisControl)" class="form-control">
      <option *ngFor="let control of controls" [value]="control.ControlID"> 
      {{control.controlName}} ({{control.ControlCode}})</option>
  </select>  

This is my component code...

import { Component, OnInit, Output, EventEmitter, Input } from 
'@angular/core';
import { msControlDataService } from '../../services/ms-control-data- 
service';

@Component({
  selector: 'ms-control-name-id-code',
  templateUrl: './control-name-id-code.component.html',
  styleUrls: ['./control-name-id-code.component.scss']
})
export class ControlNameIdCodeComponent implements OnInit {
  agencies: any;
  constructor(private msControlDataService:msControlDataService) { }

  ngOnInit() {
    this.getAgencies();
  }
  @Input() currYear: any;
  @Output() selectedValue = new EventEmitter<object>();
  getAgencies(){
    this.msControlDataService.getControlListAD(this.currYear)
    .subscribe((data) => {
      this.agencies = data;

    });
  }
  updateControl(control){    
    this.selectedValue.emit(control);
  }
  thisControl:string = "";

}

This is my usage in my application...

I import the Module into app.module.ts and add my tag to the html...

 <ms-control-name-id-code [(currYear)]="currYear"  
(selectedValue)="setControl($event)" ></ms-control-name-id-code> 

Like I said this all works as expected however I can't seem to figure out how to "reset" the control without doing a full page refresh or get at the ngModel of the control.

any help is greatly appreciated!!


Solution

  • So what I ended up doing was using @ViewChild to get access to all of my components properties and functions...

    @ViewChild(ControlNameIdCodeComponent)
    private resetDropDown: ControlNameIdCodeComponent;
    

    Then I can just change the value bound to ngModel

    this.resetDropDown.thisControl = "";