1

有没有办法用 ViewChild 控制孙子和嵌套组件?我需要从顶层访问/运行孙子组件中的公共方法。它似乎对我不起作用。暂时不要使用服务或输入/输出。

它对我有用,仅适用于直接子组件。

资源:

https://angular.io/api/core/ViewChild

4

2 回答 2

2

即使您说您宁愿不使用服务,这也可能是您的最佳选择。

您可以遵循解决方案。

使用@ViewChild,您可以按照指南操作,孙组件位于祖父组件中。

@Output否则,您可以使用装饰器创建从孙子到父母,然后从父母到祖父母的“桥梁” 。

子组件公开了一个 EventEmitter 属性,当发生某些事情时它会使用该属性发出事件。父级绑定到该事件属性并对这些事件作出反应。孩子的 EventEmitter 属性是一个输出属性,通常用 @Output 装饰

资源

例子:

祖父母:

<parent (notifyGrandparent)="GrandparentHandle($event)">
</parent>
 ///ts
GrandparentHandle(event){
// do needed work
}

家长:

<child (handleNotif)="childEvent($event)">
</child>
@Output() notifyGrandparent= new EventEmitter();
childEvent(event) {
  this.notifyGrandparent.emit('event')
}

孩子:

@Output() handleNotif = new EventEmitter
onNotify() {
  this.handleNotif.emit('notify everyone')
}

资源

您可以按照指南进行组件交互,并使用完整的 stackblitz 示例。

此外,您可以阅读有关组件交互的此线程

这个使用的例子@viewChildren,更有趣......

于 2020-07-28T05:27:52.577 回答
0

@ViewChild 注释允许从您的视图中获取组件,使用 is 类型或使用主题标签

-- 父组件.ts

@Component()
export class ParentComponant {

  @ViewChild("childComponent") child : ChildComponant;
  @ViewChild(ChildComponant) ifOnlyOneChildOfThisType : ChildComponant;
  
  // child are only accessible after view init
  ngAfterViewInit() {
     this.child.aPublicMethod();
     this.ifOnlyOneChildOfThisType.aPublicMethod();
  }

}

-- 父组件.html

<h1> Hello i'm the parent component </h1>
<child-component #childComponent></child-component>

如果您的子组件需要使用父组件中的方法,您可以使用 Event 或通过 Input 直接将该方法提供给子组件。

如果你给出一个方法,你必须将它声明为箭头函数,否则你会得到错误的“this”对象。

-- 父组件.ts

@Component()
export class ParentComponant {

  @ViewChild("childComponent") child : ChildComponant;
  @ViewChild(ChildComponant) ifOnlyOneChildOfThisType : ChildComponant;
  
  // child are only accessible after view init
  ngAfterViewInit() {
     this.child.aPublicMethod();
     this.ifOnlyOneChildOfThisType.aPublicMethod();
  }

  methodToShare = () => {
     // do something, and "this" is the ParentComponant
  }

}

-- 父组件.html

<h1> Hello i'm the parent component </h1>
<child-component [inputMethod]="methodToShare" #childComponent></child-component>

如果您有多个子组件,您可以使用 @ViewChildren 注释,它允许您在 Query 中获取组件列表

跳它帮助

于 2020-07-28T15:33:01.943 回答