簡體   English   中英

Angular中父子組件的數據共享

[英]Data Sharing from parent to child component in Angular

我嘗試並能夠使用 @input() 將數據從父組件發送到子組件

現在我正在嘗試在事件發生時將數據從父組件發送到子組件。 即.. 每當用戶在父組件文本框中輸入一些數據並點擊“發送到按鈕”時,它應該在子組件中顯示該值。

在此處輸入圖像描述

所以,有人可以幫我解決這個問題。 謝謝!

這是我知道的一種方式。 請搜索更多...首先,您必須創建這樣的服務並創建新的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>

如果有不清楚的事情,請告訴我。 謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM