Обновление значения в дочернем компоненте, при изменении значения в родительском компоненте - PullRequest
2 голосов
/ 07 марта 2019

Я работаю в Angular, где -

  • Я пытаюсь обновить значение в дочернем компоненте, при изменении значения в родительском компоненте

    (поскольку значение динамически поступает в родительский компонент от какого-либо другого компонента) .

Как я пытался

  • Я пытался передать данные из родительского компонента в дочерний компонент. @ Входной декоратор

  • с использованием значения @Input передается только один раз, когда компонент загружается и последний по значению не передается

Я делюсь своим кодом ниже

Родительский компонент

.html

<app-banner [tournamentType]='tournamentType'></app-banner>

.ts

дочерний компонент

.ts file

import { Component, OnInit , Input } from '@angular/core';
import { ServicesService } from '../service/services.service';

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

  @Input() tournamentType;

  sportsType : any = 1;



  constructor(private rest : ServicesService) { }

  ngOnInit() {
    console.log("this. is banner page" + this.tournamentType);
    alert('hello');

    this.loadDataFromApi(1);
  }

  loadDataFromApi(sportsType) {

     this.rest.getbanner(this.sportsType).then(res => {
       console.log('>>>$$$$$ banner >>>>>> $$$$$$$$$$');
       console.log('  @Input tournamentType; ====' + this.tournamentType );
       console.log(res);

     })
    console.log(sportsType);
  }
}

Ответы [ 2 ]

2 голосов
/ 07 марта 2019

Изменения значений от родительских к дочерним компонентам отражаются немедленно. Однако вы можете прослушивать событие изменения значения в дочернем компоненте. Подробнее о ngOnChanges

Вот пример stackblitz

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<app-child [data]="count"></app-child>

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';

  count = 0;

  constructor() {
  }

  ngOnInit(): void {
    setInterval(()=> this.updateCount(), 1000);
  }

  updateCount(): void {
    this.count++;
  }
}

child.component.html

<p>
{{data}}
</p>

child.component.ts

import { Component, OnInit, OnChanges, Input, SimpleChanges } from '@angular/core';

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

  @Input() data: any;

  constructor() { }

  ngOnInit() {
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('value changed', this.data);
  }

}
1 голос
/ 07 марта 2019

Скажите, что это ваш родительский компонент.

import { Component, ViewChild, AfterViewInit } from '@angular/core';        

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit{

    message = "hello again";
    friends:string[] = [];

    //will add friend to our list of friends array
    add(friend){
        if(friend.value){
            this.friends.push(friend.value);    
            friend.value = "";
        }
        console.log(this.friends);
    }

    ngAfterViewInit() {    

    }

}

Интерфейс родительского компонента

<div>
    <input #friend type="text" placeholder="name of friend" />
    <button type="button" (click)="add(friend)">add friend</button>
</div>

<app-to-child message="List of friends" [friends]="friends"></app-to-child>   

Теперь дочерний компонент

Используйте @Input decorator с полями, в которые вы хотите получать данные из родительского компонента.

import { Component, OnInit, Input } from '@angular/core';

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

  @Input() message:string;
  @Input() friends:string[];
  constructor() { }

  ngOnInit() {
  }

  //this will called when data is passed from parent to child.
  ngOnChanges(val){
      console.log("change detected");
      console.log(val);                
  }

}

внутри child.component.html

  <h5>CHILD COMPONENT</h5>
  <p>Message : {{message}}</p>
  <div *ngFor="let friend of friends"> {{friend}}</div>

Вы можете узнать больше о component interactions здесь , быстрой прогулке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...