Angular:使用ViewChild访问孙子和嵌套组件方法

3
有没有办法使用ViewChild控制Grandchildren和嵌套组件?我需要从顶层访问/运行Grandchild组件中的公共方法。对我来说似乎不起作用。现在最好不要使用服务或输入/输出。
它对我来说只适用于直接子组件。
资源:

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


4
为什么不选择一项服务呢?这应该通过服务完成。 - undefined
请问你能否在StackBlitz上创建一个示例,展示你想要实现的内容? - undefined
如果你不想使用服务,只需在父组件和祖父组件中添加一个公共的ViewChild属性,然后从祖父组件中调用this.parentRef.grandChildRef.method... - undefined
2个回答

3
即使您说您不想使用服务,但那可能是您最好的选择。
您可以采用 this 解决方案。
使用 @ViewChild,您可以按照 this 指南,在祖父组件中使用孙子组件。
否则,您可以从孙子到父亲创建一个“桥梁”,然后再从父亲到祖父,使用 @Output 装饰器。

当发生某些事情时,子组件会公开一个 EventEmitter 属性来发出事件。父组件绑定到该事件属性并对这些事件作出反应。 子级 EventEmitter 属性是输出属性,通常带有 @Output 修饰符

source

示例:

祖父组件:

<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的示例,更加有趣...


输入输出被用于解决方案,你提供的链接也利用了服务。 - user13889515

0

@ViewChild注解允许从视图中获取一个组件,可以使用类型或者使用哈希标签

-- parent.component.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();
  }

}

-- parent.component.html

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

如果你的子组件需要使用父组件的方法,你可以使用事件(Event)或直接通过输入(Input)来给予子组件该方法。

如果你传递一个方法,你必须将其声明为箭头函数,否则会得到错误的 "this" 对象。

-- parent.component.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
  }

}

-- parent.component.html

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

如果你有多个子组件,你可以使用@ViewChildren注解,它允许你获取查询中的组件列表。
希望对你有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接