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

typescript – Angular2子属性更改不限制绑定属性的更新

发布时间:2020-12-17 09:28:57 所属栏目:安全 来源:网络整理
导读:我有一个简单的自定义指令与输入,我绑定到我的组件.但是无论什么原因,在更改input属性的子属性时,ngOnchanges()方法不会触发. my.component.ts import {Component} from 'angular2/core';import {MyDirective} from './my.directive';@Component({ directive
我有一个简单的自定义指令与输入,我绑定到我的组件.但是无论什么原因,在更改input属性的子属性时,ngOnchanges()方法不会触发.

my.component.ts

import {Component} from 'angular2/core';
import {MyDirective} from './my.directive';

@Component({
    directives: [MyDirective],selector: 'my-component',templateUrl: 'Template.html'
})

export class MyComponent {
    test: { one: string; } = { one: "1" }

    constructor( ) {
        this.test.one = "2";
    }
    clicked() {
        console.log("clicked");
        var test2: { one: string; } = { one :"3" };
        this.test = test2; // THIS WORKS - because I'm changing the entire object
        this.test.one = "4"; //THIS DOES NOT WORK - ngOnChanges is NOT fired=
    }
}

my.directive.ts

import {Directive,Input} from 'angular2/core';
import {OnChanges} from 'angular2/core';

@Directive({
    selector: '[my-directive]',inputs: ['test']
})

export class MyDirective implements OnChanges {
    test: { one: string; } = { one: "" }

    constructor() { }

    ngOnChanges(value) {
        console.log(value);
    }
}

template.html

<div (click)="clicked()"> Click to change </div>
<div my-directive [(test)]="test">

谁能告诉我为什么?

事实上,这是一个正常的行为,Angular2不支持深入的比较.这只是基于参考比较.看到这个问题: https://github.com/angular/angular/issues/6458.

那就是说,他们是一些解决方法,通知该对象中某些字段已被更新.

>从组件引用指令

export class AppComponent {
  test: { one: string; } = { one: '1' }
  @ViewChild(MyDirective) viewChild:MyDirective;

  clicked() {
    this.test.one = '4';
    this.viewChild.testChanged(this.test);
  }
}

在这种情况下,显式调用该指令的testChanged方法.看到这个plunkr:https://plnkr.co/edit/TvibzkWUKNxH6uGkL6mJ?p=preview.
>在服务中使用事件

一个专门的服务定义了testChanged事件

export class ChangeService {
  testChanged: EventEmitter;

  constructor() {
    this.testChanged = new EventEmitter();
  }
}

组件使用服务来触发testChanged事件:

export class AppComponent {
  constructor(service:ChangeService) {
    this.service = service;
  }

  clicked() {
    this.test.one = '4';
    this.service.testChanged.emit(this.test);
  }
}

该指令订阅此testChanged事件以便通知

export class MyDirective implements OnChanges,OnInit {
  @Input()
  test: { one: string; } = { one: "" }

  constructor(service:ChangeService) {
    service.testChanged.subscribe(data => {
      console.log('test object updated!');
    });
  }
}

希望它能帮助你,蒂埃里

(编辑:李大同)

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

    推荐文章
      热点阅读