angular 父组件给子组件传值 使用 OnChanges() 在子组件内触发事件

子组件内使用@Input定义值product 

import { Component, Input} from '@angular/core';
import {ProductModel} from '../../models/ProductModel';

@Component({
  selector: "details_main",
  templateUrl: './details.html',
  styleUrls: ['./details.scss'],
  providers: [],
})
export class DetailsComponent {

  @Input() product:ProductModel;

  constructor(
  ) {}

  
}

父组件

<details_main [product]="value"></details_main>

当父组件的value发生改变时 便会将值传到子组件

如果想在父组件传值时 在子组件内触发事件来编辑父组件传到子组件的值可使用OnChanges()

首先加如SimoleChanges

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

然后使用ngOnChanges函数

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes)
  }

最终代码如下 这时父组件传值时就可以在子组件触发OnChanges()事件了

import { Component, Input, SimpleChanges } from '@angular/core';
import {ProductModel} from '../../models/ProductModel';

@Component({
  selector: "details_main",
  templateUrl: './details.html',
  styleUrls: ['./details.scss'],
  providers: [],
})
export class DetailsComponent {

  @Input() product:ProductModel;

  constructor(
  ) {}

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes)
    console.log(product)
  }


}



猜你喜欢

转载自blog.csdn.net/qq_39785489/article/details/79708876