【问题标题】:Updating value in the child component , on value changes in the parent component在父组件的值更改时更新子组件中的值
【发布时间】:2019-07-28 23:37:05
【问题描述】:

我在 Angular 工作,在哪里 -

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

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

我是如何尝试的

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

  • 当组件加载和 后面的值没有通过

我在下面分享我的代码

父组件

.html

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

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

【问题讨论】:

  • tournamentType 是对象还是数组?
  • 分享您的 parent.componen.ts 代码

标签: angular angular5 angular6


【解决方案1】:

从父组件到子组件的值更改会立即反映。但是,您可以在子组件中侦听值更改事件。阅读更多关于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);
  }
}

【讨论】:

    【解决方案2】:

    说这是你的父组件。

        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 装饰器与要从父组件接收数据的字段一起使用。

        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 here 的信息,快速浏览。

    【讨论】:

    • 实现 OnChanges
    猜你喜欢
    • 2019-08-27
    • 2020-02-14
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2020-07-25
    • 2022-01-13
    相关资源
    最近更新 更多