Unable to access the members which are instantiated in one method in another method in Angular












2















I am able to store the data of user.id in the displayFn() function into the sourceId and print it in the console, but when I am trying to access it in the onClick() even after the displayFn() is called it shows undefined in the console. Please don't mind if this is silly question. Below is my code for the component. Thanks in advance.



import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { DataService } from '../data.service';
import { Router } from '@angular/router'
import { Global } from './Global'
import { LocationsService } from '../locations.service';

export class Locations {
id: string;
value: string;
}
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
loc: Locations = ;
sourceId: number;
destinationId: number;
myControl1 = new FormControl();
myControl = new FormControl();
filteredOptions1: Observable<Locations>;
filteredOptions: Observable<Locations>;

constructor(private router: Router, private locations: LocationsService) {}

ngOnInit() {

this.locations.getLocations().subscribe(
data => {
for (var i = 0; data[i] != null; i++) {
this.loc.push(data[i]);
}
},
error => {
console.log("error in receiving data");
},
);

this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | Locations>(''),
map(value => typeof value === 'string' ? value : value.value),
map(name => name ? this._filter(name) : this.loc.slice())
);

this.filteredOptions1 = this.myControl1.valueChanges
.pipe(
startWith<string | Locations>(''),
map(value => typeof value === 'string' ? value : value.value),
map(name => name ? this._filter1(name) : this.loc.slice())

);
}

displayFn(user: Locations): string {

this.sourceId = parseInt(user.id);
console.log("sourceId = " + this.sourceId);
return user.value;
}

private _filter(name: string): Locations {

const filterValue = name.toLowerCase();
return this.loc.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0);
}

public displayFn1(user: Locations): string {

this.destinationId = parseInt(user.id);
console.log("destinationId = " + this.destinationId);
return user.value;
}

private _filter1(name1: string): Locations {
const filterValue1 = name1.toLowerCase();
return this.loc.filter(option1 => option1.value.toLowerCase().indexOf(filterValue1) === 0);
}

onClick() {

console.log("from onclick, sourceID = " + this.sourceId);
console.log("from onclick, sourceID = " + this.destinationId);
this.router.navigate(['/services', this.sourceId,this. destinationId]);
}
}


Below is my HTML which uses Angular material Autocomplete Form.



<form>
<input type="text" placeholder="To" matInput [formControl]="myControl" [matAutocomplete]="auto" id="toPlaceName"
class="ajxPlaceCs ui-autocomplete-input">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.value}}
</mat-option>
</mat-autocomplete>

<input type="text" placeholder="From" matInput [formControl]="myControl1" [matAutocomplete]="auto1" id="fromPlaceName"
class="ajxPlaceCs ui-autocomplete-input">
<mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn1">
<mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
{{option1.value}}
</mat-option>
</mat-autocomplete>
<input type="button" name="searchBtn" (click)="onClick()" id="searchBtn" class="chkavailabilityBtn"
value="Check Availability" title="Search">
</form>









share|improve this question



























    2















    I am able to store the data of user.id in the displayFn() function into the sourceId and print it in the console, but when I am trying to access it in the onClick() even after the displayFn() is called it shows undefined in the console. Please don't mind if this is silly question. Below is my code for the component. Thanks in advance.



    import { Component, OnInit } from '@angular/core';
    import { FormControl } from '@angular/forms';
    import { Observable } from 'rxjs';
    import { map, startWith } from 'rxjs/operators';
    import { DataService } from '../data.service';
    import { Router } from '@angular/router'
    import { Global } from './Global'
    import { LocationsService } from '../locations.service';

    export class Locations {
    id: string;
    value: string;
    }
    @Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
    loc: Locations = ;
    sourceId: number;
    destinationId: number;
    myControl1 = new FormControl();
    myControl = new FormControl();
    filteredOptions1: Observable<Locations>;
    filteredOptions: Observable<Locations>;

    constructor(private router: Router, private locations: LocationsService) {}

    ngOnInit() {

    this.locations.getLocations().subscribe(
    data => {
    for (var i = 0; data[i] != null; i++) {
    this.loc.push(data[i]);
    }
    },
    error => {
    console.log("error in receiving data");
    },
    );

    this.filteredOptions = this.myControl.valueChanges
    .pipe(
    startWith<string | Locations>(''),
    map(value => typeof value === 'string' ? value : value.value),
    map(name => name ? this._filter(name) : this.loc.slice())
    );

    this.filteredOptions1 = this.myControl1.valueChanges
    .pipe(
    startWith<string | Locations>(''),
    map(value => typeof value === 'string' ? value : value.value),
    map(name => name ? this._filter1(name) : this.loc.slice())

    );
    }

    displayFn(user: Locations): string {

    this.sourceId = parseInt(user.id);
    console.log("sourceId = " + this.sourceId);
    return user.value;
    }

    private _filter(name: string): Locations {

    const filterValue = name.toLowerCase();
    return this.loc.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0);
    }

    public displayFn1(user: Locations): string {

    this.destinationId = parseInt(user.id);
    console.log("destinationId = " + this.destinationId);
    return user.value;
    }

    private _filter1(name1: string): Locations {
    const filterValue1 = name1.toLowerCase();
    return this.loc.filter(option1 => option1.value.toLowerCase().indexOf(filterValue1) === 0);
    }

    onClick() {

    console.log("from onclick, sourceID = " + this.sourceId);
    console.log("from onclick, sourceID = " + this.destinationId);
    this.router.navigate(['/services', this.sourceId,this. destinationId]);
    }
    }


    Below is my HTML which uses Angular material Autocomplete Form.



    <form>
    <input type="text" placeholder="To" matInput [formControl]="myControl" [matAutocomplete]="auto" id="toPlaceName"
    class="ajxPlaceCs ui-autocomplete-input">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
    {{option.value}}
    </mat-option>
    </mat-autocomplete>

    <input type="text" placeholder="From" matInput [formControl]="myControl1" [matAutocomplete]="auto1" id="fromPlaceName"
    class="ajxPlaceCs ui-autocomplete-input">
    <mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn1">
    <mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
    {{option1.value}}
    </mat-option>
    </mat-autocomplete>
    <input type="button" name="searchBtn" (click)="onClick()" id="searchBtn" class="chkavailabilityBtn"
    value="Check Availability" title="Search">
    </form>









    share|improve this question

























      2












      2








      2


      0






      I am able to store the data of user.id in the displayFn() function into the sourceId and print it in the console, but when I am trying to access it in the onClick() even after the displayFn() is called it shows undefined in the console. Please don't mind if this is silly question. Below is my code for the component. Thanks in advance.



      import { Component, OnInit } from '@angular/core';
      import { FormControl } from '@angular/forms';
      import { Observable } from 'rxjs';
      import { map, startWith } from 'rxjs/operators';
      import { DataService } from '../data.service';
      import { Router } from '@angular/router'
      import { Global } from './Global'
      import { LocationsService } from '../locations.service';

      export class Locations {
      id: string;
      value: string;
      }
      @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
      })
      export class HomeComponent implements OnInit {
      loc: Locations = ;
      sourceId: number;
      destinationId: number;
      myControl1 = new FormControl();
      myControl = new FormControl();
      filteredOptions1: Observable<Locations>;
      filteredOptions: Observable<Locations>;

      constructor(private router: Router, private locations: LocationsService) {}

      ngOnInit() {

      this.locations.getLocations().subscribe(
      data => {
      for (var i = 0; data[i] != null; i++) {
      this.loc.push(data[i]);
      }
      },
      error => {
      console.log("error in receiving data");
      },
      );

      this.filteredOptions = this.myControl.valueChanges
      .pipe(
      startWith<string | Locations>(''),
      map(value => typeof value === 'string' ? value : value.value),
      map(name => name ? this._filter(name) : this.loc.slice())
      );

      this.filteredOptions1 = this.myControl1.valueChanges
      .pipe(
      startWith<string | Locations>(''),
      map(value => typeof value === 'string' ? value : value.value),
      map(name => name ? this._filter1(name) : this.loc.slice())

      );
      }

      displayFn(user: Locations): string {

      this.sourceId = parseInt(user.id);
      console.log("sourceId = " + this.sourceId);
      return user.value;
      }

      private _filter(name: string): Locations {

      const filterValue = name.toLowerCase();
      return this.loc.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0);
      }

      public displayFn1(user: Locations): string {

      this.destinationId = parseInt(user.id);
      console.log("destinationId = " + this.destinationId);
      return user.value;
      }

      private _filter1(name1: string): Locations {
      const filterValue1 = name1.toLowerCase();
      return this.loc.filter(option1 => option1.value.toLowerCase().indexOf(filterValue1) === 0);
      }

      onClick() {

      console.log("from onclick, sourceID = " + this.sourceId);
      console.log("from onclick, sourceID = " + this.destinationId);
      this.router.navigate(['/services', this.sourceId,this. destinationId]);
      }
      }


      Below is my HTML which uses Angular material Autocomplete Form.



      <form>
      <input type="text" placeholder="To" matInput [formControl]="myControl" [matAutocomplete]="auto" id="toPlaceName"
      class="ajxPlaceCs ui-autocomplete-input">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{option.value}}
      </mat-option>
      </mat-autocomplete>

      <input type="text" placeholder="From" matInput [formControl]="myControl1" [matAutocomplete]="auto1" id="fromPlaceName"
      class="ajxPlaceCs ui-autocomplete-input">
      <mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn1">
      <mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
      {{option1.value}}
      </mat-option>
      </mat-autocomplete>
      <input type="button" name="searchBtn" (click)="onClick()" id="searchBtn" class="chkavailabilityBtn"
      value="Check Availability" title="Search">
      </form>









      share|improve this question














      I am able to store the data of user.id in the displayFn() function into the sourceId and print it in the console, but when I am trying to access it in the onClick() even after the displayFn() is called it shows undefined in the console. Please don't mind if this is silly question. Below is my code for the component. Thanks in advance.



      import { Component, OnInit } from '@angular/core';
      import { FormControl } from '@angular/forms';
      import { Observable } from 'rxjs';
      import { map, startWith } from 'rxjs/operators';
      import { DataService } from '../data.service';
      import { Router } from '@angular/router'
      import { Global } from './Global'
      import { LocationsService } from '../locations.service';

      export class Locations {
      id: string;
      value: string;
      }
      @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
      })
      export class HomeComponent implements OnInit {
      loc: Locations = ;
      sourceId: number;
      destinationId: number;
      myControl1 = new FormControl();
      myControl = new FormControl();
      filteredOptions1: Observable<Locations>;
      filteredOptions: Observable<Locations>;

      constructor(private router: Router, private locations: LocationsService) {}

      ngOnInit() {

      this.locations.getLocations().subscribe(
      data => {
      for (var i = 0; data[i] != null; i++) {
      this.loc.push(data[i]);
      }
      },
      error => {
      console.log("error in receiving data");
      },
      );

      this.filteredOptions = this.myControl.valueChanges
      .pipe(
      startWith<string | Locations>(''),
      map(value => typeof value === 'string' ? value : value.value),
      map(name => name ? this._filter(name) : this.loc.slice())
      );

      this.filteredOptions1 = this.myControl1.valueChanges
      .pipe(
      startWith<string | Locations>(''),
      map(value => typeof value === 'string' ? value : value.value),
      map(name => name ? this._filter1(name) : this.loc.slice())

      );
      }

      displayFn(user: Locations): string {

      this.sourceId = parseInt(user.id);
      console.log("sourceId = " + this.sourceId);
      return user.value;
      }

      private _filter(name: string): Locations {

      const filterValue = name.toLowerCase();
      return this.loc.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0);
      }

      public displayFn1(user: Locations): string {

      this.destinationId = parseInt(user.id);
      console.log("destinationId = " + this.destinationId);
      return user.value;
      }

      private _filter1(name1: string): Locations {
      const filterValue1 = name1.toLowerCase();
      return this.loc.filter(option1 => option1.value.toLowerCase().indexOf(filterValue1) === 0);
      }

      onClick() {

      console.log("from onclick, sourceID = " + this.sourceId);
      console.log("from onclick, sourceID = " + this.destinationId);
      this.router.navigate(['/services', this.sourceId,this. destinationId]);
      }
      }


      Below is my HTML which uses Angular material Autocomplete Form.



      <form>
      <input type="text" placeholder="To" matInput [formControl]="myControl" [matAutocomplete]="auto" id="toPlaceName"
      class="ajxPlaceCs ui-autocomplete-input">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{option.value}}
      </mat-option>
      </mat-autocomplete>

      <input type="text" placeholder="From" matInput [formControl]="myControl1" [matAutocomplete]="auto1" id="fromPlaceName"
      class="ajxPlaceCs ui-autocomplete-input">
      <mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn1">
      <mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
      {{option1.value}}
      </mat-option>
      </mat-autocomplete>
      <input type="button" name="searchBtn" (click)="onClick()" id="searchBtn" class="chkavailabilityBtn"
      value="Check Availability" title="Search">
      </form>






      javascript angular typescript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 9:50









      Pavan SistaPavan Sista

      318




      318
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Try updating your [displayWith]="displayFn" to [displayWith]="displayFn.bind(this)".



          You can check here for more information.






          share|improve this answer
























          • Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

            – Pavan Sista
            Nov 21 '18 at 11:46











          • You can accept the answer if your issue can be solved by answer.

            – Karan
            Nov 21 '18 at 11:59











          • I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

            – Pavan Sista
            Nov 22 '18 at 5:33











          • You can not upvote but as you have asked the question you can accept the answer.

            – Karan
            Nov 22 '18 at 6:32











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409298%2funable-to-access-the-members-which-are-instantiated-in-one-method-in-another-met%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Try updating your [displayWith]="displayFn" to [displayWith]="displayFn.bind(this)".



          You can check here for more information.






          share|improve this answer
























          • Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

            – Pavan Sista
            Nov 21 '18 at 11:46











          • You can accept the answer if your issue can be solved by answer.

            – Karan
            Nov 21 '18 at 11:59











          • I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

            – Pavan Sista
            Nov 22 '18 at 5:33











          • You can not upvote but as you have asked the question you can accept the answer.

            – Karan
            Nov 22 '18 at 6:32
















          1














          Try updating your [displayWith]="displayFn" to [displayWith]="displayFn.bind(this)".



          You can check here for more information.






          share|improve this answer
























          • Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

            – Pavan Sista
            Nov 21 '18 at 11:46











          • You can accept the answer if your issue can be solved by answer.

            – Karan
            Nov 21 '18 at 11:59











          • I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

            – Pavan Sista
            Nov 22 '18 at 5:33











          • You can not upvote but as you have asked the question you can accept the answer.

            – Karan
            Nov 22 '18 at 6:32














          1












          1








          1







          Try updating your [displayWith]="displayFn" to [displayWith]="displayFn.bind(this)".



          You can check here for more information.






          share|improve this answer













          Try updating your [displayWith]="displayFn" to [displayWith]="displayFn.bind(this)".



          You can check here for more information.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 11:18









          KaranKaran

          3,3912425




          3,3912425













          • Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

            – Pavan Sista
            Nov 21 '18 at 11:46











          • You can accept the answer if your issue can be solved by answer.

            – Karan
            Nov 21 '18 at 11:59











          • I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

            – Pavan Sista
            Nov 22 '18 at 5:33











          • You can not upvote but as you have asked the question you can accept the answer.

            – Karan
            Nov 22 '18 at 6:32



















          • Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

            – Pavan Sista
            Nov 21 '18 at 11:46











          • You can accept the answer if your issue can be solved by answer.

            – Karan
            Nov 21 '18 at 11:59











          • I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

            – Pavan Sista
            Nov 22 '18 at 5:33











          • You can not upvote but as you have asked the question you can accept the answer.

            – Karan
            Nov 22 '18 at 6:32

















          Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

          – Pavan Sista
          Nov 21 '18 at 11:46





          Thank you, that's the answer, actually I have another stupid way of doing it, but your answer is perfect.

          – Pavan Sista
          Nov 21 '18 at 11:46













          You can accept the answer if your issue can be solved by answer.

          – Karan
          Nov 21 '18 at 11:59





          You can accept the answer if your issue can be solved by answer.

          – Karan
          Nov 21 '18 at 11:59













          I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

          – Pavan Sista
          Nov 22 '18 at 5:33





          I did, but the minimum reputation to vote is 15 and i have 11. Thanks anyway.

          – Pavan Sista
          Nov 22 '18 at 5:33













          You can not upvote but as you have asked the question you can accept the answer.

          – Karan
          Nov 22 '18 at 6:32





          You can not upvote but as you have asked the question you can accept the answer.

          – Karan
          Nov 22 '18 at 6:32




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409298%2funable-to-access-the-members-which-are-instantiated-in-one-method-in-another-met%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents