簡體   English   中英

如何使用* ngIf Angular2在Input中傳遞組件引用

[英]How to pass component reference in Input with *ngIf Angular2

我在Angular2中有2個同級組件:

<test1 *ngIf="data"  [data] = "makes" #test1R></formModel>
<testing *ngIf="data" [test1Ref]="test1R"></testing>

組件“測試”具有一個調用test1組件的功能的函數:

export class Testing{

    @Input() test1Ref: test1Component;
    constructor() { }

    testFunction($event){
        this.test1Ref.hello();
    }

我的問題是this.test1Ref是未定義的,因為test1組件具有* ngIf( <test1 *ngIf="data" ),
但是沒有* ng如果test1組件中的輸入值有錯誤( [data] = "makes" )。
如何通過* ngIf傳遞組件引用

簡而言之,你不能。 如果!data ,則必須隱藏該組件,這樣仍將設置局部變量#test1R。

<test1 [hidden]="!data" [data]="makes" #test1R></test1>

然后在ngOnInit() test1內部進行空檢查,以避免發生異常。

如果僅在設置數據后才可以執行某些代碼,請按照以下步驟進行操作:

在test1組件中聲明數據作為輸入:

export class Test1 {
  @Input() data: any;
}

通過在每次值更改時將其聲明為@Input ,Angular將調用ngOnChanges,因此現在您可以執行以下操作:

ngOnChanges(changes: SimpleChanges) {
  if(changes['data'] && changes['data'].currentValue) {
    //Do something once data is set.
  }
}

暫無
暫無

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

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