簡體   English   中英

如何從子組件訪問數據? 角度2

[英]How to access data from child component? Angular2

我已經創建了名為app-inline-edit組件,它應該像這樣使用:

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

默認情況下,它應在“ CurrentCar”下以純字符串形式顯示值,旁邊帶有鉛筆圖標。 如果用戶單擊字符串或圖標,則應使用兩個圖標來呈現“ app-select”組件:一個用於保存更改,另一個用於丟棄更改。

編輯: app-inline-edit並不總是app-select ,它也可以是不同的組件。 這是我的模板:

<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>

我試圖通過訪問它

@ViewChild('inlineEditControl') inlineEditControl: ElementRef;

但是,如果editingfalse inlineEditControlundefined 我遇到的問題是。 如果默認情況下未呈現選擇,如何訪問附加到“ app-select”的選擇值(CurrentCar)? 可能嗎?

您應該使用@ViewChild

在你的組件中

@ViewChild<AppSelectComponent> appSelectComponent: AppSelectComponent;

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


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM