首页 > 解决方案 > 当父值更改时,Angular 子组件不会更改值

问题描述

父组件通过 routerLink 从另一个组件(Home 组件)获取数据。然后它将这些数据发送到子组件。这是第一次很好地工作。我的标题中有一个搜索栏,它在主页组件页面以及父组件和子组件呈现的页面中可见。单击搜索栏中的有效条目后,我再次将idandcategory参数传递给父组件,但是,只有父组件发生变化,而子组件与之前的组件保持不变。如何在不刷新的情况下再次将值传递给孩子?

父组件 HTML:

<body>
  <h1>{{id}}</h1>
  <h1>{{category}}</h1>
  <child-component [id] = "id" [category] = "category"> </child-component>
</body>

父组件 TS:

import { Component, OnInit ,ViewChild} from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'parent-component',
  templateUrl: './parent-component.component.html'
})
export class ParentComponent implements OnInit {

  id : any
  category : any

ngOnInit() {
      this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
      this.category = params.get("media_type");})

//do other stuff

子组件 TS:

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

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

  @Input() id: any;
  @Input() category: any;

//do other stuff

标签: htmlangulartypescriptcomponents

解决方案


推荐阅读