首页 文章

Angular2:如果值没有改变,输入设置器不会拾取设置事件

提问于
浏览
4

在这里参考Angular2文档文件:[https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter](Parent to child setter),我有以下子组件代码:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'name-child',
  template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent {
  private _name = '';
  @Input()
  set name(name: string) {
    console.log("name change");
    this._name =  name;
  }
  get name(): string { return this._name; }
}

父母很简单:

import { Component } from '@angular/core';
@Component({
  selector: 'name-parent',
  template: `
  <h2>Parent </h2>
  <name-child [name]="name"></name-child>
  `
})
export class NameParentComponent {
   // somewhere on ngOnInit, set name without changing value
    ngOnInit() { 

        // get pending paged only and so on
        setTimeout(() => {
            this.name = "a";
            setTimeout(() => {
                this.name = "a";
                setTimeout(() => {
                    this.name = "a";
                },1000);

            },1000);

        },1000);
   }
}

您希望控制台在3秒内三次注销“名称更改” . 它没有,它记录一次,并忽略后续集(只有在值没有改变时才会发生这种情况) . 无论值是否发生变化,如何使输入选择设置事件?

3 回答

  • 1

    我看到两种解决方法:

    1)使用不可变值

    setTimeout(() => {
      this.name = new String("a");
        setTimeout(() => {
          this.name =  new String("a");
          setTimeout(() => {
           this.name =  new String("a");
        }, 1000);
      }, 1000);
    }, 1000);
    

    2)直接更改输入属性

    @ViewChild(NameChildComponent) child: NameChildComponent;
    
    setTimeout(() => {
      this.child.name = "a";
      setTimeout(() => {
        this.child.name = "a";
        setTimeout(() => {
          this.child.name = "a";
        }, 1000);
      }, 1000);
    }, 1000);
    
  • 0

    你明确提到的文章说

    使用setter拦截输入属性更改

    当你想要实现的目标不是跟踪变化时 . 这是关于从父母到孩子发送一个事件,这是RX Subject (其中4个中的任何一个)或Angular2 EventEmitter 非常好的地方 .

    您可以在父级中创建其中一个并将其传递给子级 . 然后,在您订阅它之后,您可以跟踪所有事件而不管其值如何 .

  • 5

    如果使用输入设置器是一个严格的要求,但是你尝试过使用OnChanges,这不是正面的吗?

    import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
    @Component({
      selector: 'name-child',
      template: '<h3>"{{name}}"</h3>'
    })
    export class NameChildComponent implements OnChanges {
      @Input() name;
    
      ngOnChanges(changes: SimpleChanges) {
        if (changes['name']) {
          console.log(`Is First Change: ${changes['name'].isFirstChange}`)
          console.log(`name change from ${changes['name'].previousValue} to ${changes['name'].currentValue}`);
        }
      }
    
    }
    

相关问题