'Angular autocomplete behavior after component is loaded

In my angular application , I have a parent component with a search bar that uses autocomplete and I am displaying the results in a child component.

The autocomplete code is in the OnInit function of the parent component. On selecting a value I navigate to a different route which displays the child component. After I display the child component , the autocomplete does not work as it is called only in OnInit of the parent and the parent is already initialised.

How should I approach this problem?

Code :

parentComponent :

<form class="mx-auto row" [formGroup] = "searchForm" (ngSubmit) = "onSubmit()">
    <div class="input-group w-50 rounded mx-auto justify-content-center  rounded rounded-pill pl-3" id="input">
            <input type="text" formControlName="ticker" [(ngModel)]="selectedName" class="form-control align-middle  border-0 m-0 p-0"
            [formControl]="searchCtrl" placeholder="Enter stock ticker symbol" [matAutocomplete]="auto" >
            <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayWith" (optionSelected)="onSelected()">
                <mat-option *ngIf="!done" class="is-loading"><mat-spinner diameter="50"></mat-spinner></mat-option>
                <ng-container *ngIf="done">
                  <mat-option *ngFor="let company of companies" [value]="company">
                    <span>{{ company.description }}</span>
                    <small> | {{company.displaySymbol}}</small>
                  </mat-option>
                </ng-container>
            </mat-autocomplete>
            <div class="input-group-append">
            <button class="btn btn-outline-secondary border-0 m-2 p-0" type="submit"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
                <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
              </svg></button>
            <button class="btn  border-0 m-2 p-0" type="button" (click)="clearDisplay()"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16">
                <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
              </svg></button>
        </div>
    </div>
</form>
<ngb-alert
  *ngIf="!isValidTicker"
  type="danger"
  class="text-center mt-5 mx-auto w-50"
  (close)="invalidMessage = ''"
  >No data found. Please enter a valid !</ngb-alert>
<div *ngIf="!hasRoute('home') && isValidTicker">
    <app-display [ticker]="ticker" (parentFun)="parentFun($event)"></app-display>
</div>

Parent Component .ts file :

export class SearchDisplayComponent implements OnInit {
  //public searchForm: FormGroup;
  ticker:string='';
  companies:any;
  done!: boolean;
  selectedName: any = "";
  isValidTicker = true;
  searchCtrl = new FormControl();
  invalidMessage:any;
  searchForm = this.formBuilder.group({
    ticker:''
  });
  constructor(private http: HttpClient,private formBuilder: FormBuilder, private router : Router , private _sharedData: sharedData) {
   
   }

  ngOnInit(): void {
    
    if(this.hasRoute('home'))
    {
      this.searchForm = this.formBuilder.group({ tickerInput: '' });
      //localStorage.clear();
      console.log("Test 1");
      
      this.searchCtrl.valueChanges.pipe(
        filter(res => {
          return res !== null && res.length >= 2
        }),
        distinctUntilChanged(),
        debounceTime(300),
        tap(() => {
          //this.errorMsg = "";
          this.companies = [];
          this.done = false;
        }),
        switchMap(value => this.http.get('/api/autocomplete/'+value)
          .pipe(
            finalize(() => {
              this.done = true
            }),
          )
        )
      )
      .subscribe((data: any) => {
          var tempData = data.result;
          tempData = tempData.filter(function (el: { type: string; symbol: string | string[]; } )
          {
            return el.type == 'Common Stock' &&
            !el.symbol.includes(".")
          })
          this.companies = tempData;
          console.log(typeof(this.companies));
          console.log(JSON.stringify(this.companies));
      });
      
    }
    else
    {
      //this.searchForm = this.formBuilder.group({ ticker: localStorage.getItem('stockName') });
      //this.searchForm = this.formBuilder.group({ ticker: localStorage.getItem('stockName') });
      
    }
    
  }

After the form is submitted or a value is selected in autocomplete , I am displaying the child component , how do I continue the autocomplete feature?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source