亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android開發(fā)中父組件調(diào)用子組件方法demo

 更新時間:2022年12月13日 10:16:59   作者:Jovie  
這篇文章主要為大家介紹了Android開發(fā)中父組件調(diào)用子組件方法demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

在一些非常罕見的情況下,你可能需要直接從父組件中調(diào)用子組件的方法。一般來說,這應(yīng)該被看作是最后的手段。在大多數(shù)情況下,組件通信應(yīng)該限于數(shù)據(jù)綁定(包括輸入和輸出),以及在某些情況下,使用服務(wù)在兩個組件之間發(fā)送值。

然而,有些時候,我在兩個組件之間出現(xiàn)了競賽條件,而這些條件只有通過非常精確的方法調(diào)用順序才能解決。這意味著,我需要它們同步發(fā)生。為此,這個方法是一個救命稻草,而且也很簡單

考慮到我有以下組件

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
}

子組件:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
    callMe(value : string) { 
        console.log('Called : ' + value);
    }
}

在parent.component.html的視圖中,我放置了子組件:

<app-child></app-child>

現(xiàn)在在我的父組件中,我可以像這樣使用ViewChild來獲得對子組件的直接引用:

export class ParentComponent implements OnInit {
    @ViewChild(ChildComponent, {static : true}) child : ChildComponent;
}

注意,我沒有像我們有時使用ViewChild那樣傳入一個 "字符串 "來查找,我們傳入的是我們正在尋找的組件的實(shí)際類型。

組件調(diào)用

然后,這就像在我們的孩子身上調(diào)用一些東西一樣簡單:

export class ParentComponent implements OnInit {
    @ViewChild(ChildComponent, {static : true}) child : ChildComponent;
    callMyChild(){
        child.callMe('Calling from the parent!');
    }
}

然而,通常的ViewChild規(guī)則適用,一般來說,你只能在視圖初始化后訪問ViewChild引用(所以你不能在ngOnInit方法中訪問它們,你必須使用ngAfterViewInit)。

同樣,使用數(shù)據(jù)綁定或 "連接服務(wù) "來讓兩個組件進(jìn)行通信通常會好得多。但往往很難同步需要發(fā)生的動作的精確順序。因此,對于這一點(diǎn),ViewChild是贏家。

以上就是Android開發(fā)中父組件調(diào)用子組件方法demo的詳細(xì)內(nèi)容,更多關(guān)于Android父組件調(diào)用子組件的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論