Brian C
Brian C

Reputation: 1447

angular2 Child Component how to import var updated by Parent Component

I have two components that each need to use the same URL params for a server call.

The parent component has some vars with default values of '' that are then updated in the constructor. There the vars are assigned to a string from the URL parameters (determined in the app_module.ts file).

I know that the values are correctly being updated in the Parent Component, because I successfully use them in that component, however I cannot seem to pass them to the child component with the updated value.

The imported vars have the value before it was updated. How to I make sure the child can access the value from after it was updated?

Parent Component

@Component({
  selector: 'parent',
  templateUrl: './parent.ng.html',
})
export class Parent<T> {
  /** Response protobuf from the partner details service. */
  response: Observable<ParentServiceResponse>;

   /** THESE VALUES NEED TO BE ACCESSED BY CHILD */
  companyId = '';
  userId = '';
  accountId = '';

  /** VARS ARE UPDATED HERE BASED ON URL PARAMETERS */
  constructor(
      route: ActivatedRoute,
      private readonly parentServiceResponse: ParentServiceResponse) {
    this.response = route.params.pipe(
        map(params => ({
              companyId: params['company_id'],
              userId: params['user_id'],
              accountId: params['account_id'],
            })),
        concatMap(
            ids => this.parentServiceResponse.getResponse(
                ids.companyId, ids.userId, ids.accountId)),
    );
  }
}

Child Component

@Component({
  selector: 'child',
  templateUrl: './child.html',
})
export class Child implements AfterViewInit{

  /* IMPORTED VARS HERE SHOULD HAVE VALUE FROM URL PARAMS*/
  @Input() companyId: string;
  @Input() userId: string;
  @Input() accountId: string;

  ngAfterViewInit(){
    console.log("This prints blank strings")
    console.log(this.companyId)
    console.log(this.userId)
    console.log(this.accountId)
    // Call function which subscribes to Observable, using the imported vars
    this.data.pageIndex.subscribe(x => {
      this.queryAndAppendData();
    });
  }
}

Parent HTML Template

<div>
A whole bunch of unimportant stuff
</div>

<child [companyId]="companyId"
       [userId]="userId"
       [accountId]="accountId">
</child>

I realize this likely has something do async and the vars being imported before the constructor updates the values, but I'm not sure how to make it wait until the values are updated before importing them, or have it import them again once the values get updated

Upvotes: 1

Views: 69

Answers (2)

Avij
Avij

Reputation: 694

This is because nowhere you assigned the values to your component variables.

Right now you are creating an object on the fly in the map function and passing it as return from map to concat map. That is why your service gets the input. To assign it to component variables you have to use **"this.VARIABLE_NAME"**

You can do it as follows:

map(params => {
    this.companyId = params['company_id'],
    this.userId = params['user_id']
    this.accountId = params['account_id']
    // You can either return in below fashion or you can use the component variables directly in the concatMap like this.companyId etc... 
    // because you assigned the values to such variables above.
    return {
        companyId: this.companyId,
        userId: this.userId,
        accountId: this.accountId
    }
})

Upvotes: 1

kashpatel
kashpatel

Reputation: 725

You can access updated bindings inside "ngOnChanges" life cycle hook. There might be typos :). See below.

export class Child implements OnChanges {

  /* IMPORTED VARS HERE SHOULD HAVE VALUE FROM URL PARAMS*/
  @Input() companyId: string;
  @Input() userId: string;
  @Input() accountId: string;

  ngOnChanges(changes: SimpleChanges){
    console.log("This prints blank strings")
    console.log(changes.primaryId.currentValue)
    console.log(changes.userId.currentValue)
    console.log(changes.accountId.currentValue)
  }
}

Upvotes: 0

Related Questions