Android开发中父组件调用子组件方法demo

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android开发中父组件调用子组件方法demo

Jovie   2022-12-13 我要评论

正文

在一些非常罕见的情况下,你可能需要直接从父组件中调用子组件的方法。一般来说,这应该被看作是最后的手段。在大多数情况下,组件通信应该限于数据绑定(包括输入和输出),以及在某些情况下,使用服务在两个组件之间发送值。

然而,有些时候,我在两个组件之间出现了竞赛条件,而这些条件只有通过非常精确的方法调用顺序才能解决。这意味着,我需要它们同步发生。为此,这个方法是一个救命稻草,而且也很简单

考虑到我有以下组件

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

现在在我的父组件中,我可以像这样使用ViewChild来获得对子组件的直接引用:

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

注意,我没有像我们有时使用ViewChild那样传入一个 "字符串 "来查找,我们传入的是我们正在寻找的组件的实际类型。

组件调用

然后,这就像在我们的孩子身上调用一些东西一样简单:

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

然而,通常的ViewChild规则适用,一般来说,你只能在视图初始化后访问ViewChild引用(所以你不能在ngOnInit方法中访问它们,你必须使用ngAfterViewInit)。

同样,使用数据绑定或 "连接服务 "来让两个组件进行通信通常会好得多。但往往很难同步需要发生的动作的精确顺序。因此,对于这一点,ViewChild是赢家。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们