【问题标题】:@ViewChild() from another component@ViewChild() 来自另一个组件
【发布时间】:2019-05-08 06:14:17
【问题描述】:

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

<!-- component1.html -->
<ion-content #content></ion-content>

&lt;ion-content&gt; 是一个角度分量。我需要从另一个组件(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 元素或子组件。组件通过输入、输出和共享服务的方式相互协作。

标签: angular


【解决方案1】:

在您的 component1.html

<ion-content #content></ion-content>
<p> this is {{message}}</p>

在您的 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()
  }
}

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2021-03-30
    • 2019-03-10
    • 2017-01-28
    • 1970-01-01
    • 2019-10-25
    • 2012-06-26
    • 2016-08-23
    • 2013-07-24
    相关资源
    最近更新 更多