【发布时间】:2019-07-22 19:34:40
【问题描述】:
在这里使用 Angular 6。我有一个包含大约 2 个子组件的页面。 第一个有 2 个输入文本,第二个有一个下拉菜单。我的父组件只是单击按钮。
我知道我可以在我的子组件上使用 Eventemitter 并将值传递给我的父级,但是如果没有按钮单击事件,我应该如何从我的子级传递值。我尝试使用 ViewChild 哪种类型的作品,但在视图完全加载之前会有延迟。我正在使用 ViewChild 如下:
--父母--
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
<app-child></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
constructor() { }
message:string;
ngAfterViewInit() {
this.message = this.child.message
}
}
--孩子--
import { Component} from '@angular/core';
@Component({
selector: 'app-child',
template: `
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message = 'Hola Mundo!';
constructor() { }
}
我已经从https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/获取了上述前任
任何人都可以提供输入,我可以如何在不使用任何按钮单击/发射器的情况下实现从孩子传递/读取数据。
--更新--
--孩子--
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'ct-child',
templateUrl: './child.html'
})
export class ChildComponent implements OnInit {
childmessage: string = "Child Message!"
constructor() { }
ngOnInit() {}
}
--父母--
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'ct-parent',
templateUrl: './parent.html'
})
export class ParentComponent implements OnInit {
constructor() { }
message: string;
getDataFromChild(child1): void {
this.message = child1.message;
}
ngOnInit() {}
}
--父级HTML--
Message: {{message}}
<ct-child #child1></ct-metadata>
<button type="button" (click)="getDataFromChild(child1)">Click Me!</button>
我已经按照 cmets 进行了上述尝试,但这不起作用。
【问题讨论】:
-
@Output 不是按钮单击事件。你想从孩子那里送回什么?
-
@AnjilDhamala 我的父母有按钮单击事件,当用户按下按钮单击时,我想从第一个子组件读取 2 文本框的值并从第二个子组件读取下拉值。例如在上面的帖子中,如何将子组件中的消息值传递给父组件。
-
@Pvl 我们真的有事件处理程序吗?
-
您始终可以创建一个共享数据服务,所有组件都可以从中提取和存储数据。
标签: javascript angular