【问题标题】:Get a variable in child from parent, triggering it from the parent component从父组件获取子组件中的变量,从父组件触发它
【发布时间】:2021-09-27 17:05:59
【问题描述】:

我很难理解这一点。

我有一个组件,我将变量传递给如下:

 <app-selectcomp [plid]="plid" [codeId]="selectedCode" (notify)="getCompFromChild($event)"></app-selectcomp>

我传递了两个变量:plid 和 codeId。

使用这两个变量,有一些用户操作会创建一个名为 response.data 的数组

我能够将 response.data 发送到父组件,如下所示:

@Output() notify: EventEmitter<string> = new EventEmitter<string>(); 
this.notify.emit(this.response.data)

然后,在父组件上

getCompFromChild(values): void {}

所有这一切都很好,除了为了在父组件中获取数据,我必须从子组件触发它,例如,通过单击按钮。

我找不到获取 response.data 值的方法,它存在于子组件中,但直接来自父组件,例如通过单击父组件上的按钮。

<button type="submit" (click)="getDatainChild()">Get Child Data</button>

谢谢。

【问题讨论】:

  • 有一些用户操作会创建一个数组 - 你说......所以......你可以触发发射吗?

标签: angular typescript


【解决方案1】:

您可以使用@ViewChild() 通过从父组件引用子组件来获得所需的行为。按照这种方法,父组件将能够调用子组件的公共方法。像这样的:

在您的父组件 (.ts) 中:

@ViewChild('selectComp') selectComp: SelectComponent; <= specify the type of your child component

在你的父组件(.html)中

<app-selectcomp #selectComp [plid]="plid" [codeId]="selectedCode" 
       (notify)="getCompFromChild($event)">
</app-selectcomp>

在您的子组件 (.ts) 中创建一个将由父组件调用的方法

public getData() { }

现在,您可以在父组件中调用子组件的getData()方法了。

selectComp.getData();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多