加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

检测由父角度2触发的子组件变量的变化

发布时间:2020-12-17 07:22:53 所属栏目:安全 来源:网络整理
导读:我有2个文件. app.ts和Child.ts 我正在从app发送一个变量给孩子,我想检测变量的任何变化并相应地显示数据.我无法检测到变量的变化. 任何帮助?我附上了Plunker Link,我还在评论中解释了我想在Child.ts文件中做什么 App.ts文件 //our root app componentimpor
我有2个文件. app.ts和Child.ts

我正在从app发送一个变量给孩子,我想检测变量的任何变化并相应地显示数据.我无法检测到变量的变化.

任何帮助?我附上了Plunker Link,我还在评论中解释了我想在Child.ts文件中做什么

App.ts文件

//our root app component
import {Component,NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChildCom} from './child.ts'

@Component({
    selector: 'my-app',template: `
    <div>
        <h2>Hello</h2>
        <child-com newdata={{data}}></child-com>
    </div>
    `,})
export class App {
    data: any = [];

      constructor(){
          this.data = [{"name":"control","status":"false"}];
    }
}

@NgModule({
    imports: [ BrowserModule ],declarations: [ App,ChildCom ],bootstrap: [ App ]
})
export class AppModule {}

Child.ts文件

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

@Component({
  selector: 'child-com',template: `
    <div>
      <p>Controls: {{newdata}}</p>
    </div>
  `,})

export class ChildCom {
  @Input() newdata: any = [];

  constructor(){
  }

  // here I want to check if value of control in newdata variable is false 
  // then display message on front end "your controls are not working"
  // if value of control in newdata variable is true
  // then display message on front end "your controls are working fine."
  // this should automatically happen whenever I change the value of newdata variable
}

Plunker Link

您可以将newData设置为setter,也可以实现OnChanges
export class ChildCom {
  private _newdata: any = [];
  @Input() 
  set newdata(value) {
    // code here
  }
}
export class ChildCom implements OnChanges {
  @Input() set newdata(: any = [];

  ngOnChanges(changes) {
    // code here
  }
}

https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

暗示

newdata={{data}}

很好,但只支持字符串值

[newdata]=data

支持所有类型的值.

这是更新的plnkr的链接,解释相同,https://plnkr.co/edit/5ahxWJ?p=preview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读