在父组件中的值更改时更新子组件中的值

Tes*_*rag 6 angular angular5 angular6

我在 Angular 工作,在那里 -

  • 我正在尝试根据父组件中的值更改更新子组件中的值

    (因为值是从其他组件动态传到父组件的)

我是如何尝试的

  • 我尝试使用 @Input 装饰器将数据从父组件传递到子组件

  • 使用 @Input 值仅在组件加载时传递一次,而后者不传递值

我在下面分享我的代码

父组件

.html

<app-banner [tournamentType]='tournamentType'></app-banner>
Run Code Online (Sandbox Code Playgroud)

.ts

子组件

.ts 文件

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Pan*_*ash 10

从父组件到子组件的值更改会立即反映出来。但是,您可以侦听子组件中的值更改事件。阅读更多关于ngOnChanges

这是stackblitz的一个例子

应用程序组件.html

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

<app-child [data]="count"></app-child>
Run Code Online (Sandbox Code Playgroud)

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++;
  }
}
Run Code Online (Sandbox Code Playgroud)

子组件.html

<p>
{{data}}
</p>
Run Code Online (Sandbox Code Playgroud)

子组件.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);
  }

}
Run Code Online (Sandbox Code Playgroud)