@ViewChild 来自另一个组件

分享于2023年05月08日 angular 问答
【问题标题】:@ViewChild() from another component@ViewChild() 来自另一个组件
【发布时间】:2023-05-07 09:29:01
【问题描述】:

我有一个带有模板的组件(component1):



<ion-content> 是一个角度分量。我需要从另一个组件(component2)获取离子含量组件。

在 component1 中,我可以使用 @ViewChild() 指令来做到这一点:

@Component({
    selector: "app-component1",
    templateUrl: "./component1.html"
})
export class Component1 {
    @ViewChild('content') content: IonContent;
    // or @ViewChild(IonContent) content: IonContent;
}

但是如何在 Component2 中获取 ion-content 组件?

  • @ViewChild() 在 DOM 中搜索元素,因此只要其他组件在 DOM 中,您应该可以使用模板变量或组件类访问它。 angular.io/api/core/ViewChild
  • 什么是component2。更重要的是,你想达到什么目的?您应该很少访问 dom 元素或子组件。组件通过输入、输出和共享服务的方式相互协作。

【解决方案1】:

在您的 component1.html


this is {{message}}

在您的 component1.ts

@Component({
    selector: "app-component1",
    templateUrl: "./component1.html"
})
export class Component1 {
    message: string;
    @ViewChild('content') content: IonContent;//or @ViewChild(IonContent)content:IonContent;

    constructor(private changeDetectorRef: ChangeDetectorRef) { }

  ngAfterViewInit() {    
    console.log(this.content.message);  //message being variable in IonContent
    this.message = this.content.message;
    this.changeDetectorRef.detectChanges()
  }
}

【讨论】: