日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

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

作者:Jovie ? 更新時(shí)間: 2023-01-11 編程語(yǔ)言

正文

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

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

考慮到我有以下組件

@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來(lái)獲得對(duì)子組件的直接引用:

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

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

組件調(diào)用

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

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

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

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

原文鏈接:https://juejin.cn/post/7176280435138232381

欄目分類
最近更新