Konrad Klimczak
Konrad Klimczak

Reputation: 1534

How to access data from child component? Angular2

I have created component named app-inline-edit and it is supposed to be used like this:

<app-inline-edit (onSave)="saveEditCheck($event)">
    <app-select formControlName="CurrentCar" [options]="carOptions"></app-select>
</app-inline-edit>

By default it should show value under "CurrentCar" as plain string with pencil icon next to it. If user clicks on string or icon it should render "app-select" component with two icons: one for saving changes, the other for discarding them.

EDIT: Child of app-inline-edit does not always be the app-select, it can be also different component. This is the template I have:

<div>
  <div *ngIf="editing">
    <div #inlineEditControl class="inline-edit-input">
      <ng-content></ng-content>
    </div>
    <i class="fa fa-check" aria-hidden="true" (click)="save()"></i>
    <i class="fa fa-times" aria-hidden="true" (click)="discard()"></i>
  </div>
  <div *ngIf="!editing">
    <div title="Click to edit" (focus)="edit(value);" tabindex="0" class="inline-edit">
        {{value}}&nbsp;<i class="fa fa-pencil" aria-hidden="true" (click)="edit(value)"></i>
    </div>
  </div>
</div>

I've tried to access it via

@ViewChild('inlineEditControl') inlineEditControl: ElementRef;

But when editing is false inlineEditControl is undefined. The problem I've run into is. How can I access selected value (CurrentCar) attached to "app-select" if by default select is not rendered? Is it even possible?

Upvotes: 0

Views: 68

Answers (1)

Aravind
Aravind

Reputation: 41581

You should be using @ViewChild to that

In your component

@ViewChild<AppSelectComponent> appSelectComponent: AppSelectComponent;

this.appSelectComponent.options /////////////// have it here


<app-select formControlName="CurrentCar" [options]="carOptions"></app-select>

Upvotes: 1

Related Questions