【问题标题】:Data Sharing from parent to child component in AngularAngular中从父组件到子组件的数据共享
【发布时间】:2020-07-16 07:28:33
【问题描述】:

我尝试使用 @input() 将数据从父组件发送到子组件

现在我正在尝试根据事件将数据从父组件发送到子组件。即.. 每当用户在父组件文本框中输入一些数据并点击“发送到按钮”时,它应该在子组件中显示该值。

那么,有人可以帮我解决这个问题吗?谢谢!

【问题讨论】:

  • 你能在这里显示你的代码以便我们找到问题吗?
  • 已经有很多类似的问题了,请搜索或查看文档angular.io/guide/…。您的选项是拦截输入值更改,发出自定义事件,甚至使用单独的服务进行通信,尽管此选项通常是兄弟组件交互的最佳选择
  • 这能回答你的问题吗? Child listens for parent event in Angular 2
  • 你忘了在这里解释问题@

标签: angular


【解决方案1】:

这是我知道的。请搜索更多... 首先,你必须创建一个这样的服务并创建新的 BehaviorSubject,

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InitialService {

  value = new BehaviorSubject<string>(null);

  constructor() { }

  setValue(inputValue) {
    this.value.next(inputValue);
  }

  getValue(): Observable<string> {
    return this.value.asObservable();
  }
}

接下来,你可以像这样创建父component.ts(考虑我使用了app组件),

import { Component } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { InitialService } from './services/initial.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  value = new BehaviorSubject<string>(null);

  constructor(private initialService: InitialService) { }

  onClickMe(inputValue) {
    this.initialService.setValue(inputValue);
  }

  getValue(): Observable<string> {
    return this.value.asObservable();
  }
}

你的父组件.html,

<h1>Parent Component</h1>
<input #inputValue type="text">
<button (click)="onClickMe(inputValue.value)">Send to Child</button>
<app-child></app-child>

你的子组件.ts,

import { Component, OnInit } from '@angular/core';
import { InitialService} from '../../services/initial.service'
import { Observable } from 'rxjs';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  value: Observable<string>;

  constructor(private initialservice: InitialService) {
    this.value = initialservice.getValue();
  }

  ngOnInit() {
  }

}

你的子组件 html,

<h1>Child Component</h1>
<p>value: {{value | async}}</p>

如果有不清楚的地方,请告诉我。谢谢。

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2021-08-28
    • 2017-11-23
    • 2022-01-19
    • 2022-11-04
    • 2018-07-29
    • 2019-02-12
    • 2018-07-07
    • 2021-03-03
    相关资源
    最近更新 更多